40 lines
1.1 KiB
Plaintext
40 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Dispatchers should not be hardcoded when using `withContext` or creating new coroutines using `launch` or `async`. Injectable dispatchers ease testing by allowing tests to inject more deterministic dispatchers.
|
|
|
|
You can use default values for the dispatcher constructor arguments to eliminate the need to specify them explicitly in the production caller contexts.
|
|
|
|
This rule raises an issue when it finds a hard-coded dispatcher being used in `withContext` or when starting new coroutines.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,kotlin]
|
|
----
|
|
class ExampleClass {
|
|
suspend fun doSomething() {
|
|
withContext(Dispatchers.Default) { // Noncompliant: hard-coded dispatcher
|
|
...
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,kotlin]
|
|
----
|
|
class ExampleClass(
|
|
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
|
|
) {
|
|
suspend fun doSomething() {
|
|
withContext(dispatcher) {
|
|
...
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://developer.android.com/kotlin/coroutines/coroutines-best-practices#inject-dispatchers[Inject dispatchers] (Android coroutines best practices)
|