Adds the given observer to the observers list within the lifespan of the given owner. The events are dispatched on the main thread. If LiveData already has data set, it will be delivered to the observer. The observer will only receive events if the owner is in Lifecycle.State#STARTED or
(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer)
| 188 | * @param observer The observer that will receive the events |
| 189 | */ |
| 190 | @MainThread |
| 191 | public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) { |
| 192 | assertMainThread("observe"); |
| 193 | if (owner.getLifecycle().getCurrentState() == DESTROYED) { |
| 194 | // ignore |
| 195 | return; |
| 196 | } |
| 197 | LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer); |
| 198 | ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper); |
| 199 | if (existing != null && !existing.isAttachedTo(owner)) { |
| 200 | throw new IllegalArgumentException("Cannot add the same observer" |
| 201 | + " with different lifecycles"); |
| 202 | } |
| 203 | if (existing != null) { |
| 204 | return; |
| 205 | } |
| 206 | owner.getLifecycle().addObserver(wrapper); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Adds the given observer to the observers list. This call is similar to |
no test coverage detected