![](/img/trans.png)
[英]How to execute setTitle() for an ActionBar in an activity's observe call for a ViewModel's LiveData object?
[英]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.