user5699130
user5699130

Reputation:

Handling error in Observable

Problem Description

I have a simple class with simple function buildUseCaseObservable. Function should do following

  1. Try to get data from Internet first
    • If succeed write data to Database
    • If failed with exceptions like: ServerUnavailable, SocketException should read data from database and also should report error.
    • If receive data, but data was null or empty, should read data from database.

Basically everything works like expected, except bold point. In case something happens while getting data from web, only onError is called and onNext is not called.

I found out that there is method called onErrorResumeNext which is basically doing what I need but in that case I'm loosing error (onError is not called, instead onNext is called)

Question

Is the such method like onCompleteWithError or if no how to implement such a thing to not lose error?

@PerActivity
public class DataInteractor extends Interactor {

    private RestService rest;
    private DataService data;

    @Inject
    AuthorsInteractor(RestService rest, DataService data) {
        this.rest = rest;
        this.data = data;
    }

    @Override
    protected Observable buildUseCaseObservable() {
        return Observable.concat(
                rest.getData().doOnNext(data -> data.setAuthors(authors)),
                data.getData())
                .first(data -> data != null && !authors.isEmpty());
    }
}

Upvotes: 0

Views: 203

Answers (1)

Egor
Egor

Reputation: 40193

Unfortunately, in your case it seems like onError() and onNext() will be mutually exclusive. What I'd go with is a class that will allow you to return both the result and the error:

public static class Result<T> {
  T data;
  Throwable error;
}

then onErrorResumeNext() would look like:

.onErrorResumeNext(throwable -> new Result(data.getData(), throwable))

Upvotes: 2

Related Questions