簡體   English   中英

Android LiveData,ViewModel,無法添加具有不同生命周期的同一觀察者

[英]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嘗試解決的問題的其他解決方案。 以下是一些替代方案,取決於您的需求:

  • 全局單例 - 如果您想將一些數據保存在內存中並且可以在應用程序的任何位置訪問它,那就太棒了。 如果您希望數據“可觀察”,請將其與Rx一起使用
  • LocalBroadcastManager - 如果您想在服務和活動之間進行通信, 那就太棒了
  • 意圖 - 如果你想在服務完成后確保你的活動還活着,那就太棒了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM