Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxAndroid: when to use bindActivity and why?

Is it really necessary to use AndroidObservable.bindActivity(...) in cases like the activity below? Since you still need to unsubscribe manually in onDestroy anyway.

According to this blog post, bindActivity is necessary so:

you don't accidentally try to change state after it is valid to do so

which -the way I read it- would mean there could be issues when you do certain things with the activity after finish() is called and thus unsubscribing in onDestroy would be too late.

Can anyone give me an example of when unsubscribing as late as in onDestroy would actually be a problem?


If you look at the source for AndroidObservable.java the predicate function used for bindActivity is:

private static final Func1<Activity, Boolean> ACTIVITY_VALIDATOR = new Func1<Activity, Boolean>() {
@Override public Boolean call(Activity activity) {
        return !activity.isFinishing();
    }
};

Wouldn't it be better to also check for configuration changes, like:

private static final Func1<Activity, Boolean> ACTIVITY_VALIDATOR = new Func1<Activity, Boolean>() {
@Override public Boolean call(Activity activity) {
        return !activity.isFinishing() && !activity.isChangingConfigurations();
    }
};  

???


SomeActivity.java

public class SomeActivity extends Activity implements Observer<String> {
    private Subscription subscription;

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

        subscription = getObservable().observeOn(AndroidSchedulers.mainThread()).subscribe(this);

        // or use bindActivity here????
        // subscription = AndroidObservable.bindActivity(this, getObservable()).subscribe(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        subscription.unsubscribe();
    }

    @Override
    public void onNext(String s) {
        // do something with the activity state...
    }

    @Override public void onCompleted() {}
    @Override public void onError(Throwable throwable) {}
}
like image 560
Jaap van Hengstum Avatar asked Sep 29 '22 15:09

Jaap van Hengstum


1 Answers

You cannot do fragment transactions after onSaveInstanceState has been called, so if your subscribe opens a DialogFragment then doing that before onDestroy but after onSaveInstanceState would crash your application. This is likely to happen if the Activity is closing and a network request finishes that wants to display an error. Anything that requires saving state and so cannot be called after onSaveInstanceState would be a problem.

like image 177
Dylan Avatar answered Oct 28 '22 14:10

Dylan