如何在ViewModel中观察LiveData



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。将其移动到背景线程。

最新更新