Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RxActivityLifecycleCallbacks
package rx.android.lifecycle;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import rx.Observable;
import rx.subjects.BehaviorSubject;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
class RxActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
private static RxActivityLifecycleCallbacks instance;
private Map<Activity, BehaviorSubject<LifecycleEvent>> activityBehaviorSubjectMap;
public static final RxActivityLifecycleCallbacks getInstance(Context context) {
if (instance == null) {
instance = new RxActivityLifecycleCallbacks(context);
}
return instance;
}
private RxActivityLifecycleCallbacks(Context context) {
activityBehaviorSubjectMap = new ConcurrentHashMap<Activity, BehaviorSubject<LifecycleEvent>>();
Application application = (Application) context.getApplicationContext();
application.registerActivityLifecycleCallbacks(this);
}
public Observable<LifecycleEvent> getLifecycle(Activity activity) {
BehaviorSubject<LifecycleEvent> subject = activityBehaviorSubjectMap.get(activity);
if (subject == null) {
throw new IllegalStateException("The Activity is outside the lifecycle; cannot bind to it!");
}
return subject.asObservable();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
activityBehaviorSubjectMap.put(activity, BehaviorSubject.create(LifecycleEvent.CREATE));
}
@Override
public void onActivityStarted(Activity activity) {
activityBehaviorSubjectMap.get(activity).onNext(LifecycleEvent.START);
}
@Override
public void onActivityResumed(Activity activity) {
activityBehaviorSubjectMap.get(activity).onNext(LifecycleEvent.RESUME);
}
@Override
public void onActivityPaused(Activity activity) {
activityBehaviorSubjectMap.get(activity).onNext(LifecycleEvent.PAUSE);
}
@Override
public void onActivityStopped(Activity activity) {
activityBehaviorSubjectMap.get(activity).onNext(LifecycleEvent.STOP);
}
@Override
public void onActivityDestroyed(Activity activity) {
activityBehaviorSubjectMap.remove(activity).onNext(LifecycleEvent.DESTROY);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// Not tracked
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.