Date Tags rxjava

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.

The set-up.  The call in the library is

doAmazingThing(int param, CallBack cb);

where the CallBack is

public interface CallBack {
  onGotResult(String value);
}

So we create a wrapper method thusly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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();
            }
          }
        }
      });
    }
  });
}

The magic happens in the middle of our created observable.  An anonymous implementation of the CallBack interface (line 6) gives us access to the subscriber passed into the call().  In this example we null-check the result from the callback (line 10).  If it is null we call the onError() of the subscriber (line 12), otherwise we onNext() the result and then onCompleted() (lines 16 and 17) as there's only the one result.  Before making those calls we check that there is a subscription, pretty standard stuff.

From here on you can use your favourite RX constructs on the Observable returned from doAmazingThingObservable()

Darren @ Æ


Comments

comments powered by Disqus