LiveData { @MainThread public void observe(LifecycleOwner owner, Observer<T> observer) { if (owner.getLifecycle().getCurrentState() == DESTROYED) { return; } LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper); if (existing != null && existing.owner != wrapper.owner) { throw new IllegalArgumentException("Cannot add the same observer" + " with different lifecycles"); } if (existing != null) { return; } owner.getLifecycle().addObserver(wrapper); wrapper.activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState())); }  @MainThread void observe(LifecycleOwner owner, Observer<T> observer); @MainThread void observeForever(Observer<T> observer); @MainThread void removeObserver(final Observer<T> observer); @MainThread void removeObservers(final LifecycleOwner owner); @Nullable T getValue(); boolean hasObservers(); boolean hasActiveObservers();  }
@Test public void testAddSameObserverIn2LifecycleOwners() { Observer<String> observer = (Observer<String>) mock(Observer.class); LifecycleOwner owner2 = mock(LifecycleOwner.class); LifecycleRegistry registry2 = new LifecycleRegistry(owner2); when(owner2.getLifecycle()).thenReturn(registry2); mLiveData.observe(mOwner, observer); Throwable throwable = null; try { mLiveData.observe(owner2, observer); } catch (Throwable t) { throwable = t; } assertThat(throwable, instanceOf(IllegalArgumentException.class)); assertThat(throwable.getMessage(), is("Cannot add the same observer with different lifecycles")); }
@Test public void testStopObservingOwner_onDestroy() { Observer<String> observer = (Observer<String>) mock(Observer.class); mRegistry.handleLifecycleEvent(ON_CREATE); mLiveData.observe(mOwner, observer); assertThat(mRegistry.getObserverCount(), is(1)); mRegistry.handleLifecycleEvent(ON_DESTROY); assertThat(mRegistry.getObserverCount(), is(0)); }