LiveData在第一次回调后删除Observer [英] LiveData remove Observer after first callback

查看:531
本文介绍了LiveData在第一次回调后删除Observer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

收到第一个结果后如何删除观察者?下面是我尝试过的两种代码方式,但是即使我删除了观察者,它们都继续接收更新.

How do I remove the observer after I receive the first result? Below are two code ways I've tried, but they both keep receiving updates even though I have removed the 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-> {});
        } );

推荐答案

您的第一个将不起作用,因为observeForever()没有绑定到任何LifecycleOwner.

Your first one will not work, because observeForever() is not tied to any LifecycleOwner.

您的第二个将不起作用,因为您没有将现有的注册观察员传递给removeObserver().

Your second one will not work, because you are not passing the existing registered observer to removeObserver().

您首先需要确定是否将LiveDataLifecycleOwner(您的活动)一起使用.我的假设是您应该使用LifecycleOwner.在这种情况下,请使用:

You first need to settle on whether you are using LiveData with a LifecycleOwner (your activity) or not. My assumption is that you should be using a LifecycleOwner. In that case, use:

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

这篇关于LiveData在第一次回调后删除Observer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆