corouitne 권장사항에서 Dispatcher를 하드코딩 하지 말라고 쓰여있는데, 그 이유는 Testable Code를 만들기 위함이다.
Android의 코루틴 권장사항 | Kotlin | Android Developers
Dependency Injection(의존 관계 주입, DI)은 객체를 직접 생성하지 않고 외부로부터 필요한 객체를 받아서 사용함으로써 객체의 생성과 사용을 분리할 수 있게 해준다. Dispatcher를 주입하면 Dispatcher를 구성할 수 있게 되고(configurable), 테스트하기가 더욱 쉬워진다는 장점이 있다.
⭐️ 잘못된 코드 예시
@InstallIn(SingletonComponent::class)
@Module
object CoroutinesScopesModule {
@Singleton
@Provides
fun providesCoroutineScope(): CoroutineScope {
return CoroutineScope(SupervisorJob() + Dispatchers.Default)
}
}
→ 해당 코드는 Dispatcher를 하드코딩 하고 있다.
💙 Dispatcher를 주입하는 코드를 만들어보자
// CoroutinesQualifiers.kt file
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class DefaultDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME)
@Qualifier
annotation class MainDispatcher
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class MainImmediateDispatcher
@Retention
@suppress
와 같이 개발 중에만 유용하고, binary 에 포함될 필요는 없는 경우에 사용한다.@Qualifier
종속 항목과 동일한 유형의 다양한 구현을 제공해야 하는 경우 @Qualifier를 사용한다.