Java Reference
In-Depth Information
. take ( maxResults );
}
At we get an Observable of the saved artist names. The higher-order functions on the Ob-
servable class are similar to those on the Stream interface, so at and we're able to
filter by artist name and nationality, in a similar manner as if we were using a Stream .
At we replace each name with its Artist object. If this were as simple as calling its con-
structor, we would obviously use the map operation. But in this case we need to compose a
sequence of calls to external web services, each of which may be done in its own thread or
on a thread pool. Consequently, we need to replace each name with an Observable repres-
enting one or more artists. So we use the flatMap operation.
We also need to limit ourselves to maxResults number of results in our search. To imple-
ment this at , we call the take method on Observable .
As you can see, the API is quite stream-like in usage. The big difference is that while a
Stream is designed to compute final results, the RxJava API acts more like CompletableFu-
ture in its threading model.
In CompletableFuture we had to pay the IOU by calling complete with a value. Because
an Observable represents a stream of events, we need the ability to push multiple values;
Example 9-16 shows how to do this.
Example 9-16. Pushing values into an Observable and completing it
observer . onNext ( "a" );
observer . onNext ( "b" );
observer . onNext ( "c" );
observer . onCompleted ();
We call onNext repeatedly, once for each element in the Observable . We can do this in a
loop and on whatever thread of execution we want to produce the values from. Once we have
finished with whatever work is needed to generate the events, we call onCompleted to signal
the end of the Observable . As well as the full-blown streaming approach, there are also sev-
eral static convenience factory methods for creating Observable instances from futures, iter-
ables, and arrays.
In a similar manner to CompletableFuture , the Observable API also allows for finishing
with an exceptional event. We can use the onError method, shown in Example 9-17 , in or-
der to signal an error. The functionality here is a little different from CompletableFu-
 
 
 
Search WWH ::




Custom Search