Raymond Zhao
Raymond Zhao

Reputation: 41

rxjava2 best practice to create an Observable from an existing Callback function

I am new to rxjava2, and I want to use it to work with my existing code to solve the ignoring Callback hell. The main task is something like the code below :

SomeTask.execute(new Callback() {
    @Override
    public void onSuccess(Data data) {
        // I want to add data into observable stream here
    }
    @Override
    public void onFailure(String errorMessage) {
        // I want to perform some different operations 
        // to errorMessage rather than the data in `onSuccess` callback.
        // I am not sure if I should split the data stream into two different Observable streams 
        // and use different Observers to accomplish different logic.
        // and I don't know how to do it.
    }
}

I have done some digging in Google and Stackoverflow, but still didn't find the perfect solution to create a observable to achieve these two goals.

  1. Wrap a existing Callback function.
  2. Process different Callback data in different logic.

Any suggestion would be a great help.

Upvotes: 3

Views: 3082

Answers (1)

Ulisses Curti
Ulisses Curti

Reputation: 61

Take a look at this article. It will help you.

Here is an possible solution to your problem (Kotlin):

Observable.create<Data> { emitter ->
        SomeTask.execute(object: Callback() {

            override void onSuccess(data: Data) {
                emitter.onNext(data)
                emitter.onComplete()
            }

            override void onFailure(errorMessage: String) {
                // Here you must pass the Exception, not the message
                emitter.onError(exception)
            }
        }
}

Do not forget to subscribe and dispose the Observable.

You must also consider using Single, Maybe or any of the other Observable types.

Upvotes: 3

Related Questions