【问题标题】:How to add paramaters to new livedata builder in the view model如何在视图模型中向新的 livedata builder 添加参数
【发布时间】:2020-04-12 21:48:33
【问题描述】:

我正在尝试将我的视图模型转换为使用来自 live data2.0 的新 livedata 构建器

在我看到的所有示例中,当您使用这种新的构建器模式时,它们都省略了如何设置参数,以这个视图模型为例,userId 没有定义

class UserViewModel : ViewModel() {

    private val repository = UserRepository()

    val user: LiveData<Response<User>> = liveData {
        val data = repository.getUser(userId) // loadUser is a suspend function.
        emit(data)
    }
}

简洁看起来很干净,但是我在哪里设置 userId 它不是一个函数。

在我公开一个接受参数的函数之前,我会更新 livedata 属性。

我在想这样的事情

class UserViewModel : ViewModel() {

    private val repository = UserRepository()

    var userId : String? = null

    val user: LiveData<Response<User>> = liveData {
        val data = repository.getUser(userId) // loadUser is a suspend function.
        emit(data)
    }
}

而且fragment可以设置id,但是如果我改变了id又想进行网络调用呢?

【问题讨论】:

    标签: mvvm android-livedata android-viewmodel mutablelivedata


    【解决方案1】:

    您可以使用 ViewModelFactory 类通过 ViewModel 传递自定义参数。 创建新类

    class UserViewModelFactory(private val user_id: String) : ViewModelProvider.NewInstanceFactory() {
    
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return UserViewModel(user_id) as T
        }
    
    }
    

    在你的片段中

    val userViewModel = ViewModelProviders.of(this,UserViewModelFactory(user_id)).get(UserViewModel::class.java)
    

    在您的视图模型中

    class UserViewModel(private val userId: String) : ViewModel() {
    

    您也可以在here查看样品以供参考

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多