繁体   English   中英

如何在 ViewModel 中观察 LiveData?

[英]How to observe on LiveData in ViewModel?

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>() {

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM