Skip to content

Instantly share code, notes, and snippets.

@noaht11
Last active August 8, 2016 04:32
Show Gist options
  • Save noaht11/73e7f058855afa2d9166 to your computer and use it in GitHub Desktop.
Save noaht11/73e7f058855afa2d9166 to your computer and use it in GitHub Desktop.
Unsubscribing from an RxJava subscription to handle orientation changes
private Subscription mDoSomethingSubscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
// Setup views
...
// Start a background task
mDoSomethingSubscription = getSomething()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
something -> {
// Display something
});
}
private Observable<...> getSomething() {
return ...;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mDoSomethingSubscription != null && !mDoSomethingSubscription.isUnsubscribed()) {
mDoSomethingSubscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment