如何注入数据类

时间:2018-11-01 14:52:35

标签: dependency-injection kotlin koin

数据类注入有问题。

数据类:

data class CoroutinesDispatcherProvider(
    val main: CoroutineDispatcher,
    val computation: CoroutineDispatcher,
    val io: CoroutineDispatcher
)

viewModel需要此数据类:

class MyViewModel(private val dispatcherProvider: CoroutinesDispatcherProvider):ViewModel() {

}

最后一个模块是:

val appModule = module {
    single { (main: CoroutineDispatcher, computation: CoroutineDispatcher, io: CoroutineDispatcher) ->
        CoroutinesDispatcherProvider(
            main,
            computation,
            io
        )
    }
    viewModel { MyViewModel(get()) }
}

但是出现错误:

Caused by: org.koin.error.BeanInstanceCreationException: Can't create definition for 'Factory [name='MyViewModel',class='com.example.myapplication.MyViewModel', binds~(androidx.lifecycle.ViewModel)]' due to error :
        Can't create definition for 'Single [name='CoroutinesDispatcherProvider',class='com.example.myapplication.CoroutinesDispatcherProvider']' due to error :
        Can't get parameter value #0 from org.koin.core.parameter.ParameterList@f87fb6

appModule有什么问题?!

1 个答案:

答案 0 :(得分:0)

由于在单个声明中使用lambda,因此应使用parametersOf()来解决依赖关系。但是您首先需要初始化provider变量,因为您的viewModel依赖于它:

data class CoroutinesDispatcherProvider(val main: CoroutineDispatcher, val computation: CoroutineDispatcher, val io: CoroutineDispatcher)

class MyViewModel(private val dispatcherProvider: CoroutinesDispatcherProvider) : ViewModel() {
    fun helloworld() {
        println("dispatcher: $dispatcherProvider")
    }
}


val appModule = module {
    single { (main: CoroutineDispatcher, computation: CoroutineDispatcher, io: CoroutineDispatcher) ->
        CoroutinesDispatcherProvider(main, computation, io)
    }
    viewModel { MyViewModel(get()) }
}


class MyKoinTest : KoinTest {
    val provider: CoroutinesDispatcherProvider by inject { parametersOf(Dispatchers.Main, Dispatchers.Default, Dispatchers.IO)}
    val viewModel: MyViewModel by inject { parametersOf(provider)}

    @Before
    fun before() {
        startKoin(listOf(appModule))
    }

    @Test
    fun test1() {
        viewModel.helloworld()
    }
}

我使用了这些依赖项(koin_version = '1.0.2'):

implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-android-scope:$koin_version"
implementation "org.koin:koin-android-viewmodel:$koin_version"
testImplementation "org.koin:koin-test:$koin_version"