[英]Android lifecycle library: Cannot add the same observer with different lifecycles
[英]Android LiveData, ViewModel, Cannot add the same observer with different lifecycles
我是android架构组件的新手,并尝试在我的活动和MyLifecycleService中使用LiveData,但有时应用程序崩溃了
IllegalArgumentException:无法添加具有不同生命周期的相同观察者
这是我的服务代码
private final MutableLiveData<SocketStatus> socketStatusMutableLiveData = OrderRxRepository.Companion.getInstance().getMldSocketStatus();
socketStatusMutableLiveData.observe(this, socketStatus -> {
if (socketStatus == null) return;
...
});
对于我的活动,我有activityViewModel类,它包含相同的livingata,这里是代码
class MyActivityViewModel: ViewModel() {
val socketStatusMutableLiveData = OrderRxRepository.instance.mldSocketStatus
}
和我活动中的代码
MyActivityViewModel viewModel = ViewModelProviders.of(this).get(MyActivityViewModel .class);
viewModel.getSocketStatusMutableLiveData().observe(this, socketStatus -> {
if (socketStatus == null) return;
...
});
tl; dr你不能用两个不同的LifecycleOwner
调用LiveData.observe()
。 在您的情况下,您的Activity是一个LifecycleOwner
,另一个是您的服务。
从Android的源代码中,您可以看到,如果已经有LifecyclerOwner
观察并且LifecyclerOwner
与您尝试观察的那个不同,则抛出此异常。
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
...
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
...
}
这解释了为什么您遇到此问题,因为您尝试使用Activity(一个LifecycleOwner
)和一个Service(一个不同的LifecycleOwner
)观察相同的LiveData。
更大的问题是,您正在尝试将LiveData用于不应该执行的操作。 LiveData
用于保存单个LifecycleOwner
数据,同时您尝试使其保存多个LifecycleOwner
数据。
您应该考虑使用LiveData
尝试解决的问题的其他解决方案。 以下是一些替代方案,取决于您的需求:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.