### Question:
LiveData { @MainThread public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) { assertMainThread("observe"); if (owner.getLifecycle().getCurrentState() == DESTROYED) { 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); }  @MainThread void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer); @MainThread void observeForever(@NonNull Observer<? super T> observer); @MainThread void removeObserver(@NonNull final Observer<? super T> observer); @SuppressWarnings("WeakerAccess") @MainThread void removeObservers(@NonNull final LifecycleOwner owner); @Nullable T getValue(); @SuppressWarnings("WeakerAccess") boolean hasObservers(); @SuppressWarnings("WeakerAccess") boolean hasActiveObservers();  }### Answer:
@Test public void testAddSameObserverIn2LifecycleOwners() { Observer<String> observer = (Observer<String>) mock(Observer.class); mLiveData.observe(mOwner, observer); Throwable throwable = null; try { mLiveData.observe(mOwner2, 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)); }
@Test public void setValue_twoObserversOneStarted_liveDataBecomesActive() { Observer<String> observer1 = mock(Observer.class); Observer<String> observer2 = mock(Observer.class); mLiveData.observe(mOwner, observer1); mLiveData.observe(mOwner2, observer2); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); verify(mActiveObserversChanged).onCall(true); }
@Test public void setValue_twoObserversOneStopped_liveDataStaysActive() { Observer<String> observer1 = mock(Observer.class); Observer<String> observer2 = mock(Observer.class); mLiveData.observe(mOwner, observer1); mLiveData.observe(mOwner2, observer2); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); mRegistry2.handleLifecycleEvent(Lifecycle.Event.ON_START); verify(mActiveObserversChanged).onCall(true); reset(mActiveObserversChanged); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); verify(mActiveObserversChanged, never()).onCall(anyBoolean()); }