2

我遇到了数据类注入的问题。

数据类:

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 有什么问题?!

4

1 回答 1

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"
于 2018-12-01T10:17:06.737 回答