Search This Blog

Converting between Completablefuture and Observable

CompletableFuture<T> from Java 8 is an advanced abstraction over a promise that value of type T will be available in the future. Observable<T> is quite similar, but it promises arbitrary number of items in the future, from 0 to infinity. These two representations of asynchronous results are quite similar to the point where Observable with just one item can be used instead of CompletableFuture and vice-versa. On the other hand CompletableFuture is more specialized and because it's now part of JDK, should become prevalent quite soon. Let's celebrate RxJava 1.0 release with a short article showing how to convert between the two, without loosing asynchronous and event-driven nature of them.

From CompletableFuture<T> to Observable<T>

CompletableFuture represents one value in the future, so turning it into Observable is rather simple. When Future completes with some value, Observable will emit that value as well immediately and close stream:

First test of not-yet-implementedFutures.toObservable() converts Future into Observable and makes sure value is propagated correctly. Second test created failed Future, replaces failure with exception's message and makes sure exception was propagated. The implementation is much shorter:

NB: Observable.fromFuture() exists, however we want to take full advantage of ComplatableFuture's asynchronous operators.

From Observable<T> to CompletableFuture<List<T>>

There are actually two ways to convert Observable to Future - creating CompletableFuture<List<T>> or CompletableFuture<T> (if we assume Observable has just one item). Let's start from the former case, described with the following test cases:

Obviously Future doesn't complete until source Observable signals end of stream. Thus Observable.never() would never complete wrapping Future, rather then completing it with empty list. The implementation is much shorter and sweeter:

The key is Observable.toList() that conveniently converts from Observable<T> and Observable<List<T>>. The latter emits one item of List<T> type when source Observable<T> finishes.

From Observable<T> to CompletableFuture<T>

Special case of the previous transformation happens when we know that CompletableFuture<T> will return exactly one item. In that case we can convert it directly to CompletableFuture<T>, rather than CompletableFuture<List<T>> with one item only. Tests first: