你好,我刚刚在学习Koin,这个Dagger2类将如何在Koin 2.0中提供?
@Singleton
open class AppExecutors(private val diskIO: Executor, private val networkIO: Executor, private val mainThread: Executor) {
@Inject
constructor() : this(
Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1),
MainThreadExecutor())
fun diskIO(): Executor {
return diskIO
}
fun networkIO(): Executor {
return networkIO
}
fun mainThread(): Executor {
return mainThread
}
private class MainThreadExecutor : Executor {
private val mainThreadHandler = Handler(Looper.getMainLooper())
override fun execute(command: Runnable) {
mainThreadHandler.post(command)
}
}
}
我试过这个:
single<AppExecutors> { AppExecutors(
Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1),
AppExecutors.MainThreadExecutor())
}
但是AppExecutors.MainThreadExecutor()
是私有的。唯一的解决方案是公开吗?
好吧,使用DI从外部注入一些私有实现细节的想法有点奇怪。
Dagger2中的解决方案也是一个技巧,它实际上是围绕依赖注入工作的。
所以你需要做一个决定:我想让它成为一个私人的实施细节吗?如果是,我建议使用默认参数值,并且仅当您需要覆盖此实现(例如用于测试)时才使用注入。
open class AppExecutors(
private val diskIO: Executor,
private val networkIO: Executor,
private val mainThread: Executor = AppExecutors.MainThreadExecutor()) {
和:
single<AppExecutors> { AppExecutors(
Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)))
}
(请记住,在Kotlin中使用默认参数值最终与在原始示例中使用多个构造函数相同。)
否则,您应该将其公开并从类中提取。