package androidx.lifecycle; import androidx.annotation.CallSuper; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.arch.core.internal.SafeIterableMap; import java.util.Iterator; import java.util.Map; public class MediatorLiveData extends MutableLiveData { private SafeIterableMap, Source> mSources = new SafeIterableMap<>(); public static class Source implements Observer { public final LiveData mLiveData; public final Observer mObserver; public int mVersion = -1; public Source(LiveData liveData, Observer observer) { this.mLiveData = liveData; this.mObserver = observer; } @Override // androidx.lifecycle.Observer public void onChanged(@Nullable V v) { if (this.mVersion != this.mLiveData.getVersion()) { this.mVersion = this.mLiveData.getVersion(); this.mObserver.onChanged(v); } } public void plug() { this.mLiveData.observeForever(this); } public void unplug() { this.mLiveData.removeObserver(this); } } @MainThread public void addSource(@NonNull LiveData liveData, @NonNull Observer observer) { Source source = new Source<>(liveData, observer); Source putIfAbsent = this.mSources.putIfAbsent(liveData, source); if (putIfAbsent != null && putIfAbsent.mObserver != observer) { throw new IllegalArgumentException("This source was already added with the different observer"); } else if (putIfAbsent == null && hasActiveObservers()) { source.plug(); } } @Override // androidx.lifecycle.LiveData @CallSuper public void onActive() { Iterator, Source>> it = this.mSources.iterator(); while (it.hasNext()) { it.next().getValue().plug(); } } @Override // androidx.lifecycle.LiveData @CallSuper public void onInactive() { Iterator, Source>> it = this.mSources.iterator(); while (it.hasNext()) { it.next().getValue().unplug(); } } @MainThread public void removeSource(@NonNull LiveData liveData) { Source remove = this.mSources.remove(liveData); if (remove != null) { remove.unplug(); } } }