2017-12-17 8 views
0

最初の結果を受け取った後、どのようにオブザーバーを削除しますか?私が試した2つのコード方法は以下の通りですが、オブザーバーを削除しても両方が更新され続けています。LiveData最初のコールバック後にObserverを削除します

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-> {}); 
     }); 

答えて

2

observeForever()がどのLifecycleOwnerに縛られていないので、あなたの最初の一つは、動作しません。

既存の登録オブザーバーをremoveObserver()に渡していないため、2番目のユーザーは機能しません。

LiveDataLifecycleOwner(あなたのアクティビティ)を使用しているかどうかをまず判断する必要があります。私の前提は、LifecycleOwnerを使用しているはずです。その場合は、

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).observe((AppCompatActivity)context, observer); 
+0

が優れています。ありがとうございました :) – galaxigirl

関連する問題