Last active
May 10, 2017 06:16
-
-
Save Bhavdip/b20748668ec58d4035a8f4508b4245c6 to your computer and use it in GitHub Desktop.
[RxJava&RxAndroid] #tags:Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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