本文介绍了jetpack 组合将参数传递给 viewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在jetpack compose中将参数传递给viewModel?

how can we pass parameter to viewModel in jetpack compose?

这是我的组合

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

这是视图模型

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,如下所示:

you need to create a factory to pass dynamic parameter to ViewModel like this:

class MyViewModelFactory(private val dbname: String) :
    ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T = MyViewModel(dbname) as T
}

然后在可组合函数中像这样使用你的工厂:

then use your factory like this in composable functions:

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

现在您可以访问 ViewModel 中的 dbname 参数:

and now you have access to dbname parameter in your ViewModel:

class MyViewModel(private val dbname) : ViewModel() {
    // ...rest of the viewModel logics here
}

这篇关于jetpack 组合将参数传递给 viewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:39