/** * Backfill if already created for boundary checking. We do a trick here for corresponding events * where we pretend something is created upon initialized state so that it assumes the * corresponding event is DESTROY. */ void backfillEvents() { @Nullable Lifecycle.Event correspondingEvent; switch (lifecycle.getCurrentState()) { case INITIALIZED: correspondingEvent = ON_CREATE; break; case CREATED: correspondingEvent = ON_START; break; case STARTED: case RESUMED: correspondingEvent = ON_RESUME; break; case DESTROYED: default: correspondingEvent = ON_DESTROY; break; } eventsObservable.onNext(correspondingEvent); }
/** * Creates a new scope for the given lifecycle owner (e.g. a Fragment or an Activity). * Note: The lifetime is * attached to the {@link android.arch.lifecycle.Lifecycle} AND the parent scope. So the returned * scope is destroyed if either of them is destroyed. */ public static Scope createScope(@Nullable Scope parent, LifecycleOwner lifecycleOwner) { Scope scope = new Scope(lifecycleOwner.toString(), parent); lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Event.ON_DESTROY) void onDestroy() { scope.destroy(); } }); if (lifecycleOwner instanceof Context) { scope.put(Android.NAME_CONTEXT, lifecycleOwner); } return scope; }
@Override protected void subscribeActual(Observer<? super Event> observer) { ArchLifecycleObserver archObserver = new ArchLifecycleObserver(lifecycle, observer, eventsObservable); observer.onSubscribe(archObserver); if (!isMainThread()) { observer.onError( new IllegalStateException("Lifecycles can only be bound to on the main thread!")); return; } lifecycle.addObserver(archObserver); if (archObserver.isDisposed()) { lifecycle.removeObserver(archObserver); } }
@OnLifecycleEvent(Event.ON_ANY) void onStateChange(LifecycleOwner owner, Event event) { if (!isDisposed()) { if (!(event == ON_CREATE && eventsObservable.getValue() == event)) { // Due to the INITIALIZED->ON_CREATE mapping trick we do in backfill(), // we fire this conditionally to avoid duplicate CREATE events. eventsObservable.onNext(event); } observer.onNext(event); } }
@OnLifecycleEvent(Event.ON_STOP) protected void stop() { Log.e(TAG, "LocationListener STOP"); }
Event getValue() { return eventsObservable.getValue(); }
ArchLifecycleObserver(Lifecycle lifecycle, Observer<? super Event> observer, BehaviorSubject<Event> eventsObservable) { this.lifecycle = lifecycle; this.observer = observer; this.eventsObservable = eventsObservable; }
@OnLifecycleEvent(Event.ON_DESTROY) private void destory() { Log.e(TAG, "LocationListener DESTORY"); }
@OnLifecycleEvent(Event.ON_ANY) private void any(LifecycleOwner owner, Lifecycle.Event event) { Log.e(TAG, "LocationListener ANY: " + event.name() + "; owner: " + owner.toString()); }