Simple RxJava mistakes and how to avoid them
1. Observable creation and error handling
Consider the following example:
public Observable<Book> getFavoriteBook(User user) { return Observable.just(user.getFavoriteBookId()) .flatMap(bookId -> bookService.getById(bookId)) .onErrorReturn(throwable -> DEFAULT_FAVORITE_BOOK); }
Focus on the error handling part. In my experience in 95% of the cases the expectation behind the statement .onErrorReturn(...);
is to ensure that the method getFavoriteBook()
is “safe”, e.g. that an exception cannot be thrown from it at all, as if it was surrounded by a giant try-catch.