Skip to content

Instantly share code, notes, and snippets.

@eltonjhony
Created April 4, 2018 16:31
Show Gist options
  • Save eltonjhony/2167e72628314aa9c83b7d7ffd8979f7 to your computer and use it in GitHub Desktop.
Save eltonjhony/2167e72628314aa9c83b7d7ffd8979f7 to your computer and use it in GitHub Desktop.
public void favoriteClicked(final long id) {
handleFavorites(id)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Boolean favoriteWasAdded) {
if (favoriteWasAdded) {
// respond to the UI appropriately
} else {
// respond to the UI appropriately
}
}
});
}
private rx.Observable<Boolean> handleFavorites(final long id) {
return rx.Observable.create(new rx.Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
// check if you will need to delete or add the favorite into DB
Favorite favorite = findFavoriteById(id);
if (favorite == null) {
addFavorite(id);
subscriber.onNext(true);
} else {
deleteFavorite(id);
subscriber.onNext(false);
}
// complete the subscriber
subscriber.onCompleted();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment