【问题标题】:How to observe on LiveData in ViewModel?如何在 ViewModel 中观察 LiveData?
【发布时间】:2021-03-11 19:15:59
【问题描述】:

在PostsByLabelViewModel 上它有MutableLiveData<String> token 这个令牌在每次滚动recyclerView 时都会更改,我需要在PostsByLabelViewModel 中观察它而不是从UI,因为我试图在recyclerView.addOnScrollListener 中更改它并且应用程序是冻结和绞死。代码如下:

public class PostsByLabelViewModel extends ViewModel {

    public static final String TAG = "PostsByLabelViewModel";

    public MutableLiveData<PostList> postListMutableLiveData = new MutableLiveData<>();
    public MutableLiveData<String> finalURL = new MutableLiveData<>();
    public MutableLiveData<String> token = new MutableLiveData<>();

    public void getPostListByLabel() {

        Log.e(TAG, finalURL.getValue());

       PostsByLabelClient.getINSTANCE().getPostListByLabel(finalURL.getValue()).enqueue(new Callback<PostList>() {
            @Override
            public void onResponse(Call<PostList> call, Response<PostList> response) {
                PostList list = response.body();

                if (list.getItems() != null) {
                    Log.e(TAG, list.getNextPageToken());
                    token.setValue(list.getNextPageToken());
                    postListMutableLiveData.setValue(list);
                }
            }

            @Override
            public void onFailure(Call<PostList> call, Throwable t) {

            }
        });
    }
}

我看到ViewModel 上有一个observe 方法,我试着像这样使用它

token.observe(PostsByLabelViewModel.this, new Observer<String>() {
                    @Override
                    public void onChanged(String s) {
                        token.setValue(s);
                    }
                });

但我遇到了运行时错误

error: incompatible types: PostsByLabelViewModel cannot be converted to LifecycleOwner
                token.observe(PostsByLabelViewModel.this, new Observer<String>() {

那么我如何在令牌上观察每次更改?

【问题讨论】:

    标签: java android android-livedata android-viewmodel


    【解决方案1】:

    我需要在PostsByLabelViewModel 中观察它,而不是从 UI 中观察。

    您可以使用observeForever。只是不要忘记在不再需要时致电removeObserver。

    ...应用程序冻结并挂起。

    您在主线程上调用PostsByLabelClient.getINSTANCE().getPostListByLabel(finalURL.getValue()).enqueue。将其移至后台线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多