3

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.

6
  • See Observable.create(). Commented Oct 12, 2017 at 12:33
  • @akarnokd emitter.onError() can only pass an exception to observer, I am not sure how to pass a customized ErrorMessage object to observer. Any ideas? Commented Oct 12, 2017 at 12:39
  • Use Pair<Data, ErrorMessage> as the type so you can have multiple of the two. Commented Oct 12, 2017 at 12:40
  • @akarnokd emmm.. not a very "pretty" way as I expected. I was wondering if there is a "split" operator or somehing like that. Thanks anyway, I will have it try. Commented Oct 12, 2017 at 12:45
  • One more thing you should look at is setting a disposable/cancellable on your emitter. In case a subscription gets disposed before you complete emitting, it will be important for you to dump resources and stop your execution of "producer". Commented Oct 12, 2017 at 14:40

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.