与 LiveData 一起使用时 return 语句有什么用

What is the use of return statement when using with LiveData

我遵循了 this 示例,集成了 ViewModelLiveData

我使用 LiveData 进行 ViewModelRepository 的通信,以及 activityViewModel 的通信

我想解决这个问题的困惑很少。

工作正常,5 秒后在 MainActivity 上显示 Toast 消息。

MainActivity

    MainViewModel homeViewModel = ViewModelProviders.of(this).get(MainViewModel.class);

    homeViewModel.getResponseval().observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            Toast.makeText(getApplicationContext(), "MainActivityObserverCalled", Toast.LENGTH_LONG).show();
        }
    });

MainViewModel

public class MainViewModel extends ViewModel {

    public MutableLiveData<String> responseval;
    private LoginRepositry loginRepositry;

    public MainViewModel(){
        loginRepositry = new LoginRepositry();
        responseval = loginRepositry.getData("username","password");
    }


    public MutableLiveData<String> getResponseval() {
        return responseval;
    }       

LoginRepositry

public class LoginRepositry {

    private MutableLiveData<String> data = new MutableLiveData<>();

    public  MutableLiveData<String> getData(String username , String userpass) {

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                data.setValue("Login Repo Set Value");

            }
        }, 5000);

        return data;
    }

这是我的 2 个问题。

所以让我们分部分来做:

Now with each method i am returning some data of type LiveData, but at the time of returning the data, the value is not set. I set it after 5 seconds data.setValue("SomeValue"), So what is the use of return here, is it only because of method return type, and does nothing in case of LiveData

如果您检查 docs,您会看到 LiveData "is an observable data holder class",因此它保存数据并且您可以观察它。这对于理解为什么要在此处返回此 LiveData 对象非常重要。通过返回它,您告诉架构的下一层(ViewModel)"hey, here is this holder, I will put some data here at some point, so observer it if you want to receive the data"。

ViewModel 不观察它,只是将它传递给下一个对此数据持有者感兴趣的实体,即 UI (LifeCycleOwner)。所以在所有者中你开始观察这个 "holder of data" 并且当新数据到达时会被警告。

In MainActivity, i used homeViewModel.getResponseval().observe to observer data, but in ViewModel, I didn't use observe, but ViewModel is still observing the Repository, and after 5 seconds MainActivity gets result. I am unable to understand whats happening here.

你需要一个 LifeCycleOwner 来观察来自 LiveData 的更新,也来自文档:“LiveData 考虑一个观察者,它由 Observer class,如果其生命周期处于 STARTED 或 RESUMED 状态,则处于活动状态。LiveData 仅通知活动观察者有关更新。”为了检测状态,它需要一个 LifeCycleOwner,这就是为什么当你有 observe 方法时你将 this 作为参数传递。这就是为什么你没有在 ViewModel.

中使用 observe