【发布时间】: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