gpt4 book ai didi

android - Jetpack Compose 将参数传递给 viewModel

转载 作者:行者123 更新时间:2023-12-04 11:24:28 37 4
gpt4 key购买 nike

我们如何将参数传递给 viewModelJetpack Compose ?
这是我的可组合

    @Composable
fun UsersList() {
val myViewModel: MyViewModel = viewModel("db2name") // pass param like this
}

这是 viewModel
    class MyViewModel(private val dbname) : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData<List<User>>().also {
loadUsers()
}
}

fun getUsers(): LiveData<List<User>> {
return users
}

private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}

最佳答案

您需要创建一个工厂来将动态参数传递给 ViewModel,如下所示:

class MyViewModelFactory(private val dbname: String) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = MyViewModel(dbname) as T
}
然后在可组合函数中使用你的工厂:
@Composable
fun UsersList() {
val myViewModel: MyViewModel =
viewModel(factory = MyViewModelFactory("db2name")) // pass param like this
}
现在您可以访问 ViewModel 中的 dbname 参数:
class MyViewModel(private val dbname) : ViewModel() {
// ...rest of the viewModel logics here
}

关于android - Jetpack Compose 将参数传递给 viewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67982230/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com