IllegalArgumentException: Cannot add the same observer with different lifecycles

@MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        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");
        }
        if (existing != null) {
            return;
        }
        owner.getLifecycle().addObserver(wrapper);
    }

LiveData有多个LifecycleOwner导致的问题,解决方案:

class SafeMutableLiveData : MutableLiveData() {

    private var lastLifecycleOwner: WeakReference? = null

    fun safeObserve(owner: LifecycleOwner, observer: Observer) {
        lastLifecycleOwner?.get()?.let {
            removeObservers(it)
        }
        lastLifecycleOwner = WeakReference(owner)
        observe(owner, observer)
    }

}

 

你可能感兴趣的:(Android,kotlin,LiveData)