![](/img/trans.png)
[英]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.