How to initialize Koin viewmodel with parameters inside a composable?
Asked Answered
N

1

9

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

Nephew answered 5/10, 2021 at 20:14 Comment(0)
P
15

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) }
                    )
Poster answered 14/10, 2021 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.