【发布时间】: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