简体   繁体   中英

How to initialize Koin viewmodel with parameters inside a composable?

My viewmodel module looks like this:

val viewModelModule = module {
    viewModel { (id: Int, user: String, email: String) ->
        MyViewModel(get(), get(), id = id, user = user, email = email)
    }
}

so the viewmodel accepts a total of five parameters, the first two being repositories, here are modules for both of them:

val firstRepositoryModule = module {
    single {
        FirstRepository()
    }
}
val secondRepositoryModule = module {
    single {
       SecondRepository()
    }
}

i'm aware of this sample code , but here the viewmodel doesn't accept any parameters, so it doesn't answer my question

As mentioned in Koin's docs we can pass parameters to ViewModel via parametersOf() function and we can get ViewModel in composable with getViewModel(parametersOf(...)).

Example of a ViewModel with two params, string with ID of object and repository. In init{} we can use both of them:

class MeaningViewModel(private val meaningID: String, private val dictRepository: DictRepository) : ViewModel() {
    init {
        viewModelScope.launch {
            val reply = dictRepository.getMeaningDetails(meaningID)
 ...
}

Koin module with repository as a singleton and ViewModel with two parameters:

val appModule = module {
    single<DictRepository> { DictRepositoryImpl() }
    
    viewModel { MeaningViewModel(get(), get()) }
    ...
}

In NavHost's composable:

composable(
    route = "meaning/{meaningID}",
    arguments = listOf(navArgument("meaningID") { type = NavType.StringType })
) { entry ->
    val meaningID = entry.arguments?.getString("meaningID") ?: ""
    val viewModel = getViewModel<MeaningViewModel>(
                        parameters = { parametersOf(meaningID) }
                    )

I solved this issue by initialising the viewmodel inside the constructor of the composable:

@Composable
fun ComposableFunction(
    id: Int, user: String, email: String,
    viewModel: MyViewModel = MyViewModel(get(), get(), id, user, email)
){
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM