36 lines
1.1 KiB
Plaintext
36 lines
1.1 KiB
Plaintext
![]() |
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
|
||
|
|
||
|
----
|
||
|
class ExampleClass {
|
||
|
suspend fun doSomething() {
|
||
|
withContext(Dispatchers.Default) { // Noncompliant: hard-coded dispatcher
|
||
|
...
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
----
|
||
|
class ExampleClass(
|
||
|
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
|
||
|
) {
|
||
|
suspend fun doSomething() {
|
||
|
withContext(dispatcher) {
|
||
|
...
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== See
|
||
|
|
||
|
* https://developer.android.com/kotlin/coroutines/coroutines-best-practices#inject-dispatchers[Inject dispatchers] (Android coroutines best practices)
|