rspec/rules/S6313/kotlin/rule.adoc

33 lines
1.2 KiB
Plaintext

== Why is this an issue?
Views should not be responsible for directly triggering coroutines. Hence, `ViewModel` classes should prefer creating coroutines instead of exposing suspending functions to perform some piece of business logic. This allows for easier testing of your application, as `ViewModel` classes can be unit tested, whereas views require instrumentation tests.
Please refer to the https://developer.android.com/kotlin/coroutines/coroutines-best-practices#viewmodel-coroutines[Android docs] for more advanced examples and mechanisms of updating the views with data generated asynchronously.
This rule raises an issue when suspending functions are exposed by classes inheriting from `ViewModel`.
=== Noncompliant code example
[source,kotlin]
----
class MyViewModel : ViewModel() {
suspend fun performAction() = suspendingWorker()
}
----
=== Compliant solution
[source,kotlin]
----
class MyViewModel : ViewModel() {
fun performAction() =
viewModelScope.launch {
suspendingWorker()
}
}
----
== Resources
* https://developer.android.com/kotlin/coroutines/coroutines-best-practices#viewmodel-coroutines[The ViewModel should create coroutines] (Android coroutines best practices)