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

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

问题描述

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

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 在第一次回调后删除观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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