Home Ask Login Register

Developers Planet

Your answer is one click away!

Zbigniew Malinowski February 2016

RxJava - error handling in subjects

I'm trying to implement a ViewModel in MVVM, providing observables as "input stream" and observer as "output stream" for view to bind.

The code below seems to work if getUser() call succeeds, but throws an uncaught exception if fails:

public class ViewModel {

    private final BehaviorSubject<String> query;
    private final BehaviorSubject<User> result;

    public ViewModel() {
        result = BehaviorSubject.create();
        query = BehaviorSubject.create();
        query.flatMap(s -> getUser(s)).subscribe(result);

        //  result = result.doOnError(e -> onError(e));    //  does not work

    Observable<String> login() {
        return result.map(user -> user.getLogin());

    Observable<String> blog() {
        return result.map(user -> user.getBlog());

    public Observer<String> queryObserver() {
        return query;

    private void onError(Throwable e) {
        Log.e(TAG, e.getMessage());

How can I get onError() method executed in case of error, without pushing anything to login and blog observables?


AndroidEx February 2016

doOnError() is a "side-action" operator, it doesn't catch the error. Should be something like:

query.flatMap(s -> getUser(s)).subscribe(result::onNext, this::onError);

Post Status

Asked in February 2016
Viewed 3,106 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life