收到第一个结果后如何移除观察者?以下是我尝试过的两种代码方式,但即使我删除了观察者,它们也会继续接收更新。
Observer observer = new Observer<DownloadItem>() {
@Override
public void onChanged(@Nullable DownloadItem downloadItem) {
if(downloadItem!= null) {
DownloadManager.this.downloadManagerListener.onDownloadManagerFailed(null, "this item already exists");
return;
}
startDownload();
model.getDownloadByContentId(contentId).removeObservers((AppCompatActivity)context);
}
};
model.getDownloadByContentId(contentId).observeForever(observer);
model.getDownloadByContentId(contentId).observe((AppCompatActivity)context, downloadItem-> {
if(downloadItem!= null) {
this.downloadManagerListener.onDownloadManagerFailed(null, "this item already exists");
return;
}
startDownload();
model.getDownloadByContentId(contentId).removeObserver(downloadItem-> {});
} );
原文由 galaxigirl 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的第一个将不起作用,因为
observeForever()
不绑定到任何LifecycleOwner
。您的第二个将不起作用,因为您没有将现有的注册观察者传递给
removeObserver()
。您首先需要确定您是否将
LiveData
与LifecycleOwner
(您的活动)一起使用。我的假设是您应该使用LifecycleOwner
。在这种情况下,请使用: