Skip to content

Instantly share code, notes, and snippets.

@Bhavdip
Last active May 10, 2017 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bhavdip/b20748668ec58d4035a8f4508b4245c6 to your computer and use it in GitHub Desktop.
Save Bhavdip/b20748668ec58d4035a8f4508b4245c6 to your computer and use it in GitHub Desktop.
[RxJava&RxAndroid] #tags:Android
//Turning Any Callback Into An Rx-observable
/**
**So, let's say you're using a library that does something amazing. Trouble is that you didn't write it and the author hasn't RX'd it yet. The call you need to use is asynchronous and returns the result by virtue of a callback. How can we make it into an Observable? Here's a way.
**/
doAmazingThing(int param, CallBack cb);
public interface CallBack {
onGotResult(String value);
}
//So we create a wrapper method thusly:
public Observable<String> doAmazingThingObservable(int param) {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
doAmazingThing(param, new CallBack() {
@Override
public void onGotResult(String result) {
if (result == null) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(new SomeException());
}
} else {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(result);
subscriber.onCompleted();
}
}
}
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment