본문 바로가기
SW Programming/Android

sonarLint / Android의 코루틴 권장사항

by Crystal.k 2022. 8. 8.

Dispatchers should be injectable
 
Code smell
 
Major
kotlin:S6310
 
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
Inject dispatchers (Android coroutines best practices)

https://developer.android.com/kotlin/coroutines/coroutines-best-practices#inject-dispatchers

반응형

댓글