我是 MVVM 的新手。所以我的 fragment/Activity 对服务器有 2 个请求,第一个请求的结果将用作第二个请求的输入参数。
所以首先在我的 fragment 中,当单击一个按钮时,我会请求检查用户是否被禁止,如果没有,那么该用户可以创建一个帖子。
所以首先我检查用户是否被禁止或没有在我的 fragment 中使用此代码
class CreateEventFragment : Fragment() {
lateinit var model: CreateEventViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
model = ViewModelProvider(this).get(CreateEventViewModel::class.java)
button.setOnClickListener {
model.checkIfUserIsBanned()
}
}
}
这是 View 模型
class CreateEventViewModel(application: Application) : AndroidViewModel(application) {
val mUserIsBanned :MutableLiveData<Boolean> = UserClient.mUserIsBanned
fun checkIfUserIsBanned(userID: String) {
UserRepository.checkIfUserIsBanned(id)
}
}
这是客户端(为简单起见,我跳过了存储库)
object UserClient {
val mUserIsBanned = MutableLiveData<Boolean>()
fun checkIfUserIsBanned(userID: String) {
// perform networking, after getting the value then
if (user.isBanned) {
mUserIsBanned.postValue(true)
} else {
mUserIsBanned.postValue(false)
}
}
}
这里是问题所在,第二个请求需要第一个结果的结果,即 mUserIsBanned
需要检查用户是否未被禁止然后执行第二个请求(用户创建帖子) .我的问题是,我应该把这个逻辑放在哪里?在 View 模型中还是在我的 fragment 中?
if (userIsBanned == false) {
createPost()
}
从我看过的教程来看,好像livedata一直是在fragment中观察到的。所以第一个选择是像这样将逻辑放在 fragment 中
model.mUserIsBanned.observe(viewLifecycleOwner, Observer { isBanned ->
val userIsBanned = isBanned ?: return@Observer
if (!userIsBanned) {
model.createPost()
}
})
可以将这样的代码检查放在 fragment 中吗?
其实我不需要观察isBanned,我只需要检查一次
或者第二个选项是在viewmodel中检查userIsBanned与否,但我不知道如何在viewmodel中进行livedata观察
还是我的方法全错了?我不确定使用这个 MVVM
求助,java也行。
最佳答案
你可以试试MediatorLiveData
为您的第二次手术。什么MediatorLiveData
确实是,它为您的各种 LiveData
创建了一个可监听的容器对象并在任何基础/观察值发生变化时为您提供回调。
示例:假设 LiveData<B>
需要调用 LiveData<A>
的任何值更改,这里可以考虑LiveData<B>
作为MediatorLiveData
.
因此 LiveData<B>
的声明会是:
val bLiveData : LiveData<B> = MediatorLiveData<B>().apply {
addSource(aLiveData) { aData ->
value = convertADataToB(aData) //value is backing property for getValue()/setValue() method, use postValue() explicitly upon bg operation
}
}
在您的情况下,将此代码放入您的 ViewModel
中:
val createPostLiveData: LiveData<Boolean> = MediatorLiveData<Boolean>().apply {
addSource(mUserIsBanned) { flag ->
if (!flag) {
createPost() // Check whether you can return result from here and provide to this mediator livedata a value
}
}
}
关于android - 我可以在我的 View 模型中创建实时数据观察器吗?还是我应该始终观察 fragment/Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60784137/