我可以在我的视图模型中做一个livedata观察者吗?还是我应该始终观察片段/活动? [英] can I make a livedata observer in my viewmodel? or should I always observer in fragment/activity?

本文介绍了我可以在我的视图模型中做一个livedata观察者吗?还是我应该始终观察片段/活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVVM的新手.因此我有2个来自我的片段/活动到服务器的请求,第一个请求的结果将用作第二个请求的输入参数.

I am new to MVVM. so I have 2 requests to the server from my fragment/activity, the result from the first request will be used as an input parameter for the second request.

首先,在我的片段中,单击一个按钮,然后我请求检查用户是否被禁止,如果没有,则该用户可以创建一个帖子.

so first in my fragment, when a button is clicked then I make a request to check whether the user is banned or not, if not then this user can create a post.

所以首先我要检查用户是否被禁止使用此代码.

so first I check if a user is banned or not using this code in my 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()
        }

    }


}

这是视图模型

class CreateEventViewModel(application: Application) : AndroidViewModel(application) {

    val mUserIsBanned :MutableLiveData<Boolean> = UserClient.mUserIsBanned

    fun checkIfUserIsBanned(userID: String) {
        UserRepository.checkIfUserIsBanned(id)
    }


}

这是客户端(为简单起见,我跳过了存储库)

and here is the client ( I skip the repository for simplicity)

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需要检查用户是否未被禁止,然后执行第二个请求(用户创建一个帖子).我的问题是,我应该把这个逻辑放在哪里?在视图模型中还是在我的片段中?

here is the problem, the second request needs the result of the first result, i.e the mUserIsBanned is need to check if the user is not banned then perform the second request (user create a post). my question is, where do I place this logic ? in viewmodel or in my fragment?

if (userIsBanned == false) {
   createPost()
}

从我所看到的教程中,似乎总是在一个片段中观察到实时数据.所以第一个选择是将逻辑放在这样的片段中

from the tutorial I have seen, it seems the livedata is always observed in a fragment. so the first option is to place the logic in fragment like this

    model.mUserIsBanned.observe(viewLifecycleOwner, Observer { isBanned ->

        val userIsBanned = isBanned ?: return@Observer

        if (!userIsBanned) {
            model.createPost()
        }

    })

可以将这样的代码检查放在一个片段中吗?

is it okay to place code checking like that in a fragment?

实际上我不需要观察isBanned,我只需要检查一次

actually I don't need to observed the isBanned, I just need to check it once

或第二个选项是在viewmodel中检查userIsBanned与否,但我不知道如何在viewmodel中进行实时数据观察

or the second option is to check userIsBanned or not in viewmodel, but I don't know how to do livedata observation in viewmodel

还是我的方法全错了?我不确定使用此MVVM

or my approach is all wrong ? I am not sure using this MVVM

请帮助,java也可以.

please help, java is also ok.

推荐答案

您可以尝试MediatorLiveData进行第二次操作. MediatorLiveData的作用是,它为您各种LiveData对象&一旦任何基础/观察值发生变化,便会为您提供回调.

You can try MediatorLiveData for your second operation. What MediatorLiveData does is, it creates a listenable container for your various LiveData objects & provide you callback once any of the underlying/observing value changes.

示例:假设在LiveData<A>的任何值更改时都需要调用LiveData<B>,在这里您可以将LiveData<B>视为MediatorLiveData.

Example: Assume that LiveData<B> needs to be called on any value changes from LiveData<A>, here you can consider LiveData<B> as 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中:

In your case, put this code inside your 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
        }
    }
}

引用 MediatorLiveData

Refer MediatorLiveData

这篇关于我可以在我的视图模型中做一个livedata观察者吗?还是我应该始终观察片段/活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆