Android 生命周期库:无法添加具有不同生命周期的相同观察者 [英] Android lifecycle library: Cannot add the same observer with different lifecycles

查看:109
本文介绍了Android 生命周期库:无法添加具有不同生命周期的相同观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用生命周期库的应用程序,但我收到一个 IllegalArgumentException,提示无法添加具有不同生命周期的相同观察者",我只在 onCreate 中添加了我认为安全的观察者.我的大多数观察者都是通过匿名类添加的,我认为这不是问题,因为观察者永远不会被回收.一种是使用this:

I have an app I'm working on that's using the lifecycle library but I'm getting an IllegalArgumentException that says "Cannot add the same observer with different lifecycles" I only add observers in onCreate which I thought would be safe. Most of my observers are added via anonymous classes which I assume can't be the issue here since the observer is never recycled. One is using this:

private GpsState gpsState;

void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getLifecycle().addObserver(gpsState);
    gpsState.observe(this, (state) -> {
        // ...
    });
}

在本例中,GpsState 扩展了 LiveData 以提供 GPS 的当前状态并实现 LifecycleObserver 以便能够在到达时刷新某些值ON_RESUME 状态.

In this example GpsState extends LiveData to provide the current state of the GPS and implements LifecycleObserver to be able to refresh certain values when reaching an ON_RESUME state.

知道我做错了什么吗?

推荐答案

就我而言,问题出在观察者的 lambda 方法为空.我只是尝试添加一些东西,问题就解决了.例如:

In my case the problem was at lambda method of observer is empty. I just tried to add something to it and problem was solved. For example:

gpsState.observe(this, (state) -> {
                Log.d(this.getClass().getSimpleName(), BaseNavigationActivity.this.toString());

});

很可能 JVM 定义了仅使用静态引用的匿名类,在这种情况下,它变得有点单例,因此您在引用此类类时将始终拥有相同的实例.

Most likely that JVM define anonymous classes that use only static references and for such cases it become kinda singleton, so you will have same instance all the time you reference such class.

这篇关于Android 生命周期库:无法添加具有不同生命周期的相同观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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