简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM