Summary of a.

RxLifecycle is a lightweight, less intrusive RxJava logout management library. He will not change the original project Activity inheritance structure, easy to achieve RxJava in the Android platform under the automatic logout, even when you use RxJava custom view can easily complete the automatic logout function. If your project wants to introduce a rXJava-related auto-logout library in the middle of development, this library is a good choice for you because it is less invasive.

Project address: Welcome star

Github.com/dhhAndroid/…

Gradle depends on:

The compile ‘com. DHH: rxlifecycle: 1.0’

Two. Use method

If RxLifecycle is injected into the Activity, please be assured that the RxLifecycle library will not reference the context reference passed in with(), so there is no need to unregister it and it will not leak memory. Implement either of the following two injection modes:

If you have a BaseActivity, just inject RxLifecycle into the BaseActivity onCreate method:


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            RxLifecycle.injectRxLifecycle(this);

        }Copy the code

Now that you have a BaseActivity, you can wrap RxLifecycle code around it:


        private <T> LifecycleTransformer<T> bindToLifecycle() {
            return RxLifecycle.with(this).bindToLifecycle();
        }

        private <T> LifecycleTransformer<T> bindOnDestroy() {
            return RxLifecycle.with(this).bindOnDestroy();
        }

        private <T> LifecycleTransformer<T> bindUntilEvent(ActivityEvent event) {
            return RxLifecycle.with(this).bindUntilEvent(event);
        }

        //use
        @Override
        protected void onStart() {
            super.onStart();
            Observable.just(1)
                    //use       
                    .compose(bindToLifecycle())
                    .subscribe();
        }
Copy the code

Or if you already have an operation that inherits from Application, you can inject RxLifecycle like this:


        public class RxLifecycleAPP extends Application {
            @Override
            public void onCreate() {
                super.onCreate();
                registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                    @Override
                    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                        RxLifecycle.injectRxLifecycle(activity);
                    }
                    //other mothods}); }}Copy the code

Note:

1. Implement one of the two ways to inject RxLifecycle if you like.

2. If you don’t subscribe to an Observable during the Activity’s “onPause” life cycle or any subsequent life cycle, inject RxLifecycle. If you subscribe to an Observable during the Activity’s “onPause” life cycle and later life cycle and use RxLifecycle.with(this).bindTolifecycle (), you must do an RxLifecycle injection step. The reason for this problem will be explained in the principle analysis section. Code examples:


    @Override
    protected void onPause() {
        super.onPause();
        Observable.just("dhhAndroid")
                // Other binding methods do not require pre-injection
                .compose(RxLifecycle.with(this).<String>bindOnDestroy())
                .subscribe();
        Observable.just(1)
                // To use bindToLifecycle() in onPause and subsequent lifecycles, RxLifecycle must be injected first
                .compose(RxLifecycle.with(this).<Integer>bindToLifecycle())
                .subscribe();
    }
Copy the code

3. For the sake of simplicity and security, I can ignore the second one and inject it all. The second one is just like I’m in a blind BB…

Use in activities and Fragments:

Simply add the compose operator to your original Observable event stream with the following code:


        Observable.timer(10, TimeUnit.SECONDS) // Automatically determine the lifecycle.compose(RxLifecycle.with(this).<Long>bindToLifecycle())
                .subscribe(a);

        Observable.timer(10, TimeUnit.SECONDS) // When the activity onStop is logged out.compose(RxLifecycle.with(this).<Long>bindUntilEvent(ActivityEvent.onStop))
                .subscribe(a);
        Observable.just("dhhAndroid") // When the activity onDestroy is destroyed.compose(RxLifecycle.with(this).<String>bindOnDestroy())
                .subscribe(a);Copy the code

RxLifecycle. With (), the with method can accept parameters such as Activity,Context(note: this Context must be able to be strongly converted into an Activity),View(currently not supported on the V7 package appxxxview),Fragment , the V4. Fragments, etc.

Use in custom view

If you can customize a view using RxJava and have retrofit+RxJava network access inside the view, it can convert RxJava operation time to data and also support a line of code to manage RxJava automatic logging to make sure your view doesn’t inherit from appxxx View, currently not supported. Same usage as in activities and fragments:


        public class MyView extends View {
            //other...

            public void doSomething(){
                Observable.timer(10, TimeUnit.SECONDS)
                        // Automatically determine the lifecycle
                        .compose(RxLifecycle.with(this).<Long>bindToLifecycle())
                        .subscribe();

                Observable.timer(10, TimeUnit.SECONDS)
                        // When the activity onStop is logged out
                        .compose(RxLifecycle.with(this).<Long>bindUntilEvent(ActivityEvent.onStop))
                        .subscribe();
                Observable.just("dhhAndroid")
                        // When the activity onDestroy is destroyed
                        .compose(RxLifecycle.with(this).<String>bindOnDestroy()) .subscribe(); . }}Copy the code

Use in other layers

When using RxLifecycle in the MVP architecture or elsewhere, just make sure that the place you’re using gets a Context that can be converted into an Activity. In the project, I wrote a with overload method that can be passed to any object as long as it can be converted to Context, or a member variable of the passed object can be converted to Context(Activity) by reflection. It can also be automatically bound to the RxJava life cycle, but it is not open for performance concerns (private) Method). You can use this idea to expand with your own projects. The code is as follows:


    private static LifecycleManager with(Object object) {
        if (object instanceof Context) {
            return with((Context) object);
        }
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object value = field.get(object);
                if (value instanceof Context) {
                    return with((Context) value); }}catch(IllegalAccessException e) { e.printStackTrace(); }}throw new ClassCastException(object.getClass().getSimpleName() + " can\'t convert Context !");
    }
Copy the code

Don’t hit me!

First of all, RxJava is an excellent asynchronous operation library, which leads to memory leaks when used on Android. Log out of the Observable event task when appropriate (typically when the Activity view onDestroy is relied on by RxJava code). So let’s talk about RxJava logout methods, and what conditions can trigger the logout.

1. Generate Subscription and unsubscribe Activity onDestroy:

    private Subscription mSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSubscription = Observable.just(1).subscribe();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mSubscription! =null&&!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }Copy the code

This approach is traditional and cumbersome, and it can be too cumbersome to log off if there are multiple network requests in the interface, or if RxBus receives data.

2. Conditional trigger, unsubscribe, and cancel Observable event flow task.

There are many conditional triggers, such as the take series of operators, which start a subscription when the condition is met, or unsubscribe. In addition, the subscription can be cancelled if certain conditions are met in the subscriber onNext() method. Another alternative method is to throw exceptions during the execution of Observable event flow, which can also achieve the purpose of cancellation. Example code:

        Observable.just(1.23.434.5454.343.346.56.67.4.-1)
                // Take the first five and cancel
                .take(5)
                // Log out until the condition is satisfied
                .takeUntil(new Func1<Integer, Boolean>() {
                    @Override
                    public Boolean call(Integer integer) {
                        return integer > 66666; }})The library uses this operator until another Observable sends data and logs out
                .takeUntil(Observable.just(1))
                .first(new Func1<Integer, Boolean>() {
                    @Override
                    public Boolean call(Integer integer) {
                        return integer = = 111; }}).map(new Func1<Integer.Integer>() {
                    @Override
                    public Integer call(Integer integer) {
                        if (integer < 0) {
                            // Throw exception logout, which is used in my other library RxProgressManager
                            throw new RuntimeException("The data cannot be less than zero.");
                        }
                        return integer; }}).subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        if (integer = = Awesome!) {
                            // Log off when the conditions are metunsubscribe(); }}});Copy the code

This library is mainly implemented by takeUntil(otherObservable). The demonstration figure of the takeUntil operator is as follows:

The original Observable unsubscribes once the otherObservable sends data. So what we need to do is wrap the Activity’s life cycle information as an Observable as otherObservable, and then send the information along with the life cycle. When the required life cycle is reached (such as onDestroy), unsubscribe. Luckily, RxJava has implemented this function for us. Subject extends Observable Implement Observer, which is a bridge between Observable and subscriber:

public abstract class Subject<T.R> extends Observable<R> implements Observer<T> {
    protected Subject(OnSubscribe<R> onSubscribe) {
        super(onSubscribe);
    }
    public abstract boolean hasObservers();

    public final SerializedSubject<T, R> toSerialized() {
        if (getClass() == SerializedSubject.class) {
            return (SerializedSubject<T, R>)this;
        }
        return new SerializedSubject<T, R>(this); }}Copy the code

RxJava already implements several XXxSubjects by default, but I won’t cover the rest, just the BehaviorSubject I’m going to use for this article , its characteristic is that when there is a subscriber subscription BehaviorSubject, the BehaviorSubject sends the last data released by the subscriber subscription BehaviorSubject to the BehaviorSubject. If the BehaviorSubject has executed onCompleted or O, the BehaviorSubject also sends the last data released by the subscriber subscription BehaviorSubject NError, the onCompleted or onError notification will be sent to the Subscriber.

  // observer will receive all 4 events (including "default").
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.subscribe(observer);
  subject.onNext("one");
  subject.onNext("two");
  subject.onNext("three");

  // observer will receive the "one"."two" and "three" events, but not "default" and "zero"
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.subscribe(observer);
  subject.onNext("two");
  subject.onNext("three");

  // observer will receive only onCompleted
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.onCompleted(a);
  subject.subscribe(observer);

  // observer will receive only onError
  BehaviorSubject<Object> subject = BehaviorSubject.create("default");
  subject.onNext("zero");
  subject.onNext("one");
  subject.onError(new RuntimeException("error"));
  subject.subscribe(observer);Copy the code

So we can do this with an Activity or Fragment (since the Fragment depends on an Activity, I consider the Fragment’s life cycle to be the same as that of an Activity in this project, with no more life cycle callbacks for the Fragment than for an Activity):


public class MainActivity extends AppCompatActivity {
    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        lifecycleSubject.onNext(ActivityEvent.onCreate);
        super.onCreate(savedInstanceState);
        Observable.just(1)
                .takeUntil(lifecycleSubject.first(new Func1<ActivityEvent, Boolean>() {
                    @Override
                    public Boolean call(ActivityEvent event) {
                        return event==ActivityEvent.onDestory;
                    }
                }))
                .subscribe();
    }

    @Override
    public void onStart() {
        lifecycleSubject.onNext(ActivityEvent.onStart);
        super.onStart();
    }

    @Override
    public void onResume() {
        lifecycleSubject.onNext(ActivityEvent.onResume);
        super.onResume();
    }

    @Override
    public void onPause() {
        lifecycleSubject.onNext(ActivityEvent.onPause);
        super.onPause();
    }

    @Override
    public void onStop() {
        lifecycleSubject.onNext(ActivityEvent.onStop);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.onDestory);
        super.onDestroy(); }}Copy the code

ActivityEvent is an enumeration that lists the Activity lifecycle:

public enum ActivityEvent {
    onCreate,
    onStart,
    onResume,
    onPause,
    onStop,
    onDestory,
}Copy the code

In this way, we send the lifecycle of the Activity one by one through lifecycleSubject, connect it to the original Observable with takeUntil as the otherObservable, and use the first operator until we receive the lifecycle we specify (o is specified above) NDestroy), an Observable that does not log out. The first operator looks like this:

Now that we’ve completed the core principle of unlogging RxJava through the Activity lifecycle, can we encapsulate this fixed operation as our own operator? Of course you can, RxJava provides two types of custom operators, one is Observable.Operator, which is connected to an Observable through the lift() Operator. This Operator transforms data and is not applicable to our application scenario. We need to use a second custom operator, Observable.Transformer, which transforms an upstream Observable:

public class LifecycleTransformer<T> implements Observable.Transformer<T, T> {
    private Observable<ActivityEvent> lifecycleObservable;
    private ActivityEvent activityEvent;

    LifecycleTransformer(Observable<ActivityEvent> lifecycleObservable, ActivityEvent activityEvent) {
        this.lifecycleObservable = lifecycleObservable;
        this.activityEvent = activityEvent;
    }

    @Override
    public Observable<T> call(Observable<T> sourceObservable) {
        return sourceObservable.takeUntil(getLifecycleObservable());
    }

    @NonNull
    privateObservable<? >getLifecycleObservable() {
        lifecycleObservable.takeFirst(new Func1<ActivityEvent, Boolean>() {
            @Override
            public Boolean call(ActivityEvent event) {
                return activityEvent == event; }}); }}Copy the code

At this point we can use the compose operator to connect our custom LifecycleTransformer to the original Observable:

        Observable.just(1)
                .compose(new LifecycleTransformer<Integer>(lifecycleSubject,ActivityEvent.onDestory))
                .subscribe(a);Copy the code

This implements exactly the same functionality as above, so we define an interface LifecycleManager to generate these LifecycleTransformer:


public interface LifecycleManager {

    Observable<ActivityEvent> getLifecycle();

    <T> LifecycleTransformer<T> bindUntilEvent(ActivityEvent activityEvent);

    <T> LifecycleTransformer<T> bindToLifecycle();

    <T> LifecycleTransformer<T> bindOnDestroy();
}
Copy the code

The interface provides four methods:

  • GetLifecycle (): A BehaviorSubject that gets the Observable that provides the lifecycle. This is called lifecycleSubject.
  • BindUntilEvent (ActivityEvent ActivityEvent): Generates the specified LifecycleTransformer based on the incoming life cycle, binding the original Observable to the specified Activity life cycle.
  • bindToLifecycle() : This is based on the original Observable subscription and the life cycle that it should be deactivated at that life cycle, such as onCreate subscriptions deactivated on OnDestroy, onStart subscriptions deactivated on onStop, onResume subscriptions deactivated on onPause Start something when the interface is visible and stop something when the interface is not, such as a wheel feed.
  • BindOnDestroy (): binds directly to Observable logout when the Activity interface is destroyed. This is a case of bindUntilEvent(ActivityEvent ActivityEvent).

BindToLifecycle () ¶


    public class LifecycleTransformer<T> implements Observable.Transformer<T, T> {
    private Observable<ActivityEvent> lifecycleObservable;

    LifecycleTransformer(Observable<ActivityEvent> lifecycleObservable) {
        this.lifecycleObservable = lifecycleObservable.share();
    }

    @Override
    public Observable<T> call(Observable<T> sourceObservable) {
        return sourceObservable.takeUntil(getLifecycleObservable());
    }

    @NonNull
    privateObservable<? >getLifecycleObservable() {
        return Observable.combineLatest(lifecycleObservable.first().map(ACTIVITY_LIFECYCLE),
                lifecycleObservable.skip(1), new Func2<ActivityEvent, ActivityEvent, Boolean>() {
                    @Override
                    public Boolean call(ActivityEvent activityEvent, ActivityEvent event) {
                        return activityEvent == event;
                    }
                })
                .takeFirst(new Func1<Boolean, Boolean>() {
                    @Override
                    public Boolean call(Boolean aBoolean) {
                        returnaBoolean; }}); }// For lifecycle transformation
    private static final Func1<ActivityEvent, ActivityEvent> ACTIVITY_LIFECYCLE =
            new Func1<ActivityEvent, ActivityEvent>() {
                @Override
                public ActivityEvent call(ActivityEvent lastEvent) {
                    switch (lastEvent) {
                        case onCreate:
                            return ActivityEvent.onDestory;
                        case onStart:
                            return ActivityEvent.onStop;
                        case onResume:
                            return ActivityEvent.onPause;
                        case onPause:
                            return ActivityEvent.onStop;
                        case onStop:
                            return ActivityEvent.onDestory;
                        case onDestory:
                            throw new IllegalStateException("Cannot injectRxLifecycle to Activity lifecycle when outside of it.");
                        default:
                            throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); }}}; }Copy the code

First of all, in the constructor, we only need to get lifecycleSubject(lifecycleObservable) this time. Instead of passing in ActivityEvent, we can use the share operator to make the lifecycleObservable have multiple subscRs iber. As a result of thislifecycleObservableA BehaviorSubject is called BehaviorSubject. As described above, when a subscriber has a BehaviorSubject, it sends the last event before subscribing to the subscriber. Using the first operator, we can get the life cycle of the original Observable subscription, and generate the subscription using the Map operator The cycle translates to the life cycle that should be logged out, so we have the life cycle of the write-out, which is basically the same logic as the constructor passing in two parameters.

Through combineLatest operator will convert the life cycle of observables (lifecycleObservable. First (). The map (ACTIVITY_LIFECYCLE)) and life cycle of observables (lifecycleOb Skip (1)) unlogs the original Observable by filtering out the data after the specified life cycle through takeFirst.

The code for incorporating the above constructors into a LifecycleTransformer is as follows:

public class LifecycleTransformer<T> implements Observable.Transformer<T, T> {
    private Observable<ActivityEvent> lifecycleObservable;
    private ActivityEvent activityEvent;

    LifecycleTransformer(Observable<ActivityEvent> lifecycleObservable) {
        this.lifecycleObservable = lifecycleObservable.share();
    }

    LifecycleTransformer(Observable<ActivityEvent> lifecycleObservable, ActivityEvent activityEvent) {
        this.lifecycleObservable = lifecycleObservable;
        this.activityEvent = activityEvent;
    }

    @Override
    public Observable<T> call(Observable<T> sourceObservable) {
        return sourceObservable.takeUntil(getLifecycleObservable());
    }

    @NonNull
    privateObservable<? >getLifecycleObservable() {
        if(activityEvent ! =null) {
            lifecycleObservable.takeFirst(new Func1<ActivityEvent, Boolean>() {
                @Override
                public Boolean call(ActivityEvent event) {
                    return activityEvent == event; }}); }return Observable.combineLatest(lifecycleObservable.first().map(ACTIVITY_LIFECYCLE),
                lifecycleObservable.skip(1), new Func2<ActivityEvent, ActivityEvent, Boolean>() {
                    @Override
                    public Boolean call(ActivityEvent activityEvent, ActivityEvent event) {
                        return activityEvent == event;
                    }
                })
                .takeFirst(new Func1<Boolean, Boolean>() {
                    @Override
                    public Boolean call(Boolean aBoolean) {
                        returnaBoolean; }}); }// For lifecycle transformation
    private static final Func1<ActivityEvent, ActivityEvent> ACTIVITY_LIFECYCLE =
            new Func1<ActivityEvent, ActivityEvent>() {
                @Override
                public ActivityEvent call(ActivityEvent lastEvent) {
                    switch (lastEvent) {
                        case onCreate:
                            return ActivityEvent.onDestory;
                        case onStart:
                            return ActivityEvent.onStop;
                        case onResume:
                            return ActivityEvent.onPause;
                        case onPause:
                            return ActivityEvent.onStop;
                        case onStop:
                            return ActivityEvent.onDestory;
                        case onDestory:
                            throw new IllegalStateException("Cannot injectRxLifecycle to Activity lifecycle when outside of it.");
                        default:
                            throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); }}}; }Copy the code

And because of thatLifecycle transformation issues, resulting in an RxLifecycle being injected when subscribing to an Observable during onPause and beyond, as discussed below.

So the next thing we need to do is get the LifecycleManager that corresponds to the Activity.

This piece I use for reference is Glide :Glide.

We know that when a Fragment is added to an Activity through the FragmentManager, it has basically the same life cycle as an Activity (ignoring everything else), so sending the Activity’s mission cycle events through the Fragment also achieves the desired effect Fragments implementationLifecycleManagerInterface is not on the line, the previous wave of code:

public class LifecycleFragment extends Fragment implements LifecycleManager {
    private final BehaviorSubject<ActivityEvent> lifecycleSubject;

    public LifecycleFragment() {
        lifecycleSubject = BehaviorSubject.create();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        lifecycleSubject.onNext(ActivityEvent.onCreate);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        lifecycleSubject.onNext(ActivityEvent.onStart);
        super.onStart();
    }

    @Override
    public void onResume() {
        lifecycleSubject.onNext(ActivityEvent.onResume);
        super.onResume();
    }

    @Override
    public void onPause() {
        lifecycleSubject.onNext(ActivityEvent.onPause);
        super.onPause();
    }

    @Override
    public void onStop() {
        lifecycleSubject.onNext(ActivityEvent.onStop);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.onDestory);
        super.onDestroy();
    }

    @Override
    public Observable<ActivityEvent> getLifecycle() {
        return lifecycleSubject.asObservable();
    }

    @Override
    public <T> LifecycleTransformer<T> bindUntilEvent(final ActivityEvent activityEvent) {
        return new LifecycleTransformer<>(lifecycleSubject, activityEvent);
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLifecycle() {
        return new LifecycleTransformer<>(lifecycleSubject);
    }

    @Override
    public <T> LifecycleTransformer<T> bindOnDestroy() {
        returnbindUntilEvent(ActivityEvent.onDestory); }}Copy the code

So we can get through thisLifecycleFragment You can get both the Activity lifecycle and the variousLifecycleTransformer.

At this point we need to get a one-to-one mapping of this ActivityLifecycleFragment namelyLifecycleManager:

public class RxLifecycle {
    private static final String FRAGMENT_TAG = "lifecycle_tag";

    public static LifecycleManager with(Activity activity) {
        FragmentManager fm = activity.getFragmentManager();
        Fragment fragment = fm.findFragmentByTag(FRAGMENT_TAG);
        if (fragment == null) {
            fragment = new LifecycleFragment();
            fm.beginTransaction().add(fragment, FRAGMENT_TAG).commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
        return (LifecycleManager) fragment;
    }Copy the code

Use the FragmentManager to add an empty LifecycleFragment TAG to the Activity, if called again with the TAG. Now that we have LifecycleManager, we can get the various LifecycleTransformer.

We want to use that Observable that subscribes to after onPausebindToLifecycleWhy inject RxLifecycle in the first place:

If you haven’t used RxLifecycle before onPause, this is a lifecycle where the interface doesn’t add an empty LifecycleFragment, resulting in a LifecycleFragment callback when the first call is made during onPause The Fragment is onCreate->onStart->onPause->onStop(there is no onResume because the Fragment is not visible at the time it is created, so it will not be called back), so when using bindToLifecycle(), the lifecycle transition will Out of question. Do your own brain work. I won’t analyze it in detail.

So I had to add a pre-injected method called in the Activity’s onCreate method:

    / * * * @param context ensure context can be cast {@link Activity}
     */
    public static void injectRxLifecycle(Context context) {
        with(context);
    }Copy the code

The with(activity) method is called, which binds the LifecycleFragment to the activity. Ensure that the lifecycle transitions are normal when bindToLifecycle() is called.If you have a better way to deal with it, please inform me in time. Thank you very much!

The RxLifecycle library can also be used in custom views, which is as simple as view.getContext(), to get the context that the view is placed on an Activity, and that context must be an Activity AppCompatXXXView and get the context is oneTintContextWrapperI couldn’t force it into an Activity. My heart was broken.Who knows how to do this? Tell me, knees up!

RxLifecycle class lifecycle

public class RxLifecycle {
    private static final String FRAGMENT_TAG = "lifecycle_tag";

    / * * * @param context ensure context can be cast {@link Activity}
     */
    public static void injectRxLifecycle(Context context) {
        with(context);
    }

    public static LifecycleManager with(Activity activity) {
        if (activity instanceof FragmentActivity) {
            return with((FragmentActivity) activity);
        }
        FragmentManager fm = activity.getFragmentManager();
        Fragment fragment = fm.findFragmentByTag(FRAGMENT_TAG);
        if (fragment == null) {
            fragment = new LifecycleFragment();
            fm.beginTransaction().add(fragment, FRAGMENT_TAG).commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
        return (LifecycleManager) fragment;
    }

    private static LifecycleManager with(FragmentActivity activity) {
        android.support.v4.app.FragmentManager fm = activity.getSupportFragmentManager();
        android.support.v4.app.Fragment fragment = fm.findFragmentByTag(FRAGMENT_TAG);
        if (fragment == null) {
            fragment = new LifecycleV4Fragment();
            fm.beginTransaction().add(fragment, FRAGMENT_TAG).commitNowAllowingStateLoss();
        }

        return (LifecycleManager) fragment;
    }

    public static LifecycleManager with(Fragment fragment) {
        return with(fragment.getActivity());
    }

    public static LifecycleManager with(android.support.v4.app.Fragment fragment) {
        return with(fragment.getActivity());
    }

    / * * * @param context ensure context can be cast {@link Activity}
     */
    public static LifecycleManager with(Context context) {
        if (context instanceof AppCompatActivity) {
            return with((FragmentActivity) context);
        }
        if (context instanceof Activity) {
            return with((Activity) context);
        }
        throw new ClassCastException(context.getClass().getSimpleName() + " can\'t cast Activity !");
    }

    public static LifecycleManager with(View view) {
        return with(view.getContext());
    }


    private static void injectRxLifecycle(Object object) {
        if (object instanceof View) {
            with((View) object);
        } else{ with(object); }}private static LifecycleManager with(Object object) {
        if (object instanceof Context) {
            return with((Context) object);
        }
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object value = field.get(object);
                if (value instanceof Context) {
                    returnwith((Context) value); }}catch(IllegalAccessException e) { e.printStackTrace(); }}throw new ClassCastException(object.getClass().getSimpleName() + " can\'t convert Context !"); }}Copy the code

About me

Project Address:Github.com/dhhAndroid/…

One of your stars is the biggest encouragement to me!