Thanh Le
Thanh Le

Reputation: 1389

Wrap legacy AsyncTask by an Observable Rxjava?

I have to use a legacy library that using AsyncTask for a background job. How I can wrap an AsyncTask by an Observable object which I'm using on my current project.

The AsyncTask is encapsulated so I cannot access the synchronous call inside AsyncTask.

Upvotes: 1

Views: 817

Answers (2)

AndroidEx
AndroidEx

Reputation: 15824

Another approach to the case when you cannot or don't want to wrap execution in an Observable is to use Subjects:

public static void main(String[] args) {
    Subject<Object, Object> subject = PublishSubject.create();

    Listener listener = new Listener() {
        @Override
        public void onCallback(Object object) {
            subject.onNext(object);
            subject.onCompleted();
        }
    };
    subject.subscribe(object -> yourReaction(object));
    someMethodWithCallback(listener);
}

public interface Listener {

    void onCallback(Object object);

}

Subject being an Observer allows you to send items into it, while it being an Observable allows you to subscribe to it and receive these events.

Upvotes: 1

krp
krp

Reputation: 2247

say you have an object asynchronousCall executing some async work with call() method which takes callback as a param, you can wrap it like that :

    Observable.create(new Observable.OnSubscribe<Object>() {
        @Override
        public void call(final Subscriber<? super Object> subscriber) {
            asynchronousCall.call(new CallBack() {
                @Override
                public void success(Object o) {
                    subscriber.onNext(o);
                    subscriber.onCompleted();
                }

                @Override
                public void error(Throwable t) {
                    subscriber.onError(t);
                }
            });
        }
    });

Upvotes: 2

Related Questions