RxJava 实践场
View at Github page
also available for reactor-core
Reactive Streams is a programming concept for handling asynchronous data streams in a non-blocking manner while providing backpressure to stream publishers. It has evolved into a specification that is based on the concept of Publisher<T> and Subscriber<T>. A Publisher is the source of events T in the stream, and a Subscriber is the consumer for those events. A Subscriber subscribes to a Publisher by invoking a "factory method" in the Publisher that will push the stream items <T> starting a new Subscription:
public interface Publisher {
public void subscribe(Subscriber s);
}When the Subscriber is ready to start handling events, it signals this via a request to that Subscription
public interface Subscription {
public void request(long n); //request n items
public void cancel();
}Upon receiving this signal, the Publisher begins to invoke Subscriber::onNext(T) for each event T. This continues until either completion of the stream (Subscriber::onComplete()) or an error occurs during processing (Subscriber::onError(Throwable)).
public interface Subscriber {
//signals to the Publisher to start sending events
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}RxJava provides more types of event publishers:
Flowable Publisher that emits 0..N elements, and then completes successfully or with an error
Observable like Flowables but without a backpressure strategy. They were introduced in RxJava 1.x
Single a specialized emitter that completes with a value successfully either an error.(doesn't have onComplete callback, instead onSuccess(val))
Maybe a specialized emitter that can complete with / without a value or complete with an error.
Completable a specialized emitter that just signals if it completed successfully or with an error.
Code is available at Part01CreateFlowable.java
Flowable flowable = Flowable.just(1, 5, 10);
Flowable flowable = Flowable.range(1, 10);
Flowable flowable = Flowable.fromArray(new String[] {"red", "green", "blue"});
Flowable flowable = Flowable.fromIterable(List.of("red", "green", "blue"));CompletableFuture completableFuture = CompletableFuture
.supplyAsync(() -> { //starts a background thread the ForkJoin common pool
log.info("CompletableFuture work starts");
Helpers.sleepMillis(100);
return "red";
});
Single single = Single.from(completableFuture);
single.subscribe(val -> log.info("Stream completed successfully : {}", val));We can use Flowable.create(...) to implement the emissions of events by calling onNext(val), onComplete(), onError(throwable)
When subscribing to the Observable / Flowable with flowable.subscribe(...) the lambda code inside create(...) gets executed. Flowable.subscribe(...) can take 3 handlers for each type of event - onNext, onError and onCompleted.
When using Observable.create(...) you need to be aware of backpressure and that Observables created with 'create' are not BackPressure aware
…Streams are lazy meaning that the code inside create() doesn't get executed without subscribing to the stream. So event if we sleep for a long time inside create() method(to simulate a costly operation), without subscribing to this Observable, the code is not executed and the method returns immediately.
public void observablesAreLazy() {
Observable observable = Observable.create(subscriber -> {
log.info("Started emitting but sleeping for 5 secs"); //this is not executed
Helpers.sleepMillis(5000);
subscriber.onNext(1);
});
log.info("Finished");
}
===========
[main] - FinishedWhen subscribing to an Observable/Flowable, the create() method gets executed for each Subscriber, the events inside create(..) are re-emitted to each subscriber independently.
So every subscriber will get the same events and will not lose any events - this behavior is named 'cold observable' See Hot Publishers to understand sharing a subscription and multicasting events.
Observable observable = Observable.create(subscriber -> {
log.info("Started emitting");
log.info("Emitting 1st event");
subscriber.onNext(1);
log.info("Emitting 2nd event");
subscriber.onNext(2);
subscriber.onComplete();
});
log.info("Subscribing 1st subscriber");
observable.subscribe(val -> log.info("First Subscriber received: {}", val));
log.info("=======================");
log.info("Subscribing 2nd subscriber");
observable.subscribe(val -> log.info("Second Subscriber received: {}", val));will output
[main] - Subscribing 1st subscriber
[main] - Started emitting
[main] - Emitting 1st event
[main] - First Subscriber received: 1
[main] - Emitting 2nd event
[main] - First Subscriber received: 2
[main] - =======================
[main] - Subscribing 2nd subscriber
[main] - Started emitting
[main] - Emitting 1st event
[main] - Second Subscriber received: 1
[main] - Emitting 2nd event
[main] - Second Subscriber received: 2Between the source Observable / Flowable and the Subscriber there can be a wide range of operators and RxJava provides lots of operators to chose from. Probably you are already familiar with functional operations like filter and map. so let's use them as example:
Flowable stream = Flowable.create(subscriber -> {
subscriber.onNext(1);
subscriber.onNext(2);
....
subscriber.onComplete();
}, BackpressureStrategy.MISSING);
.filter(val -> val val * 10)
.subscribe(val -> log.info("Received: {}", val));When we call Flowable.create() you might think that we're calling onNext(..), onComplete(..) on the Subscriber at the end of the chain, not the operators between them.
This is not true because the operators themselves are decorators for their source wrapping it with the operator behavior like an onion's layers. When we call .subscribe() at the end of the chain, Subscription propagates through the layers back to the source, each operator subscribing itself to it's wrapped source Observable / Flowable and so on to the original source, triggering it to start producing/emitting items.
Flowable.create calls ---> filterOperator.onNext(val) which if val > 10 calls ---> mapOperator.onNext(val) does val = val * 10 and calls ---> subscriber.onNext(val).
Found a nice analogy with a team of house movers, with every mover doing it's thing before passing it to the next in line until it reaches the final subscriber.
Inside the create() method, we can check is there are still active subscribers to our Flowable/Observable.
There are operators that also unsubscribe from the stream so the source knows to stop producing events.
It's a way to prevent to do extra work(like for ex. querying a datasource for entries) if no one is listening
In the following example we'd expect to have an infinite stream, but because we stop if there are no active subscribers, we stop producing events.
take(limit) is a simple operator. It's role is to count the number of events and then unsubscribes from it's source once it received the specified amount and calls onComplete() to it's subscriber.
…Code is available at Part02SimpleOperators.java
Delay operator - the Thread.sleep of the reactive world, it's pausing each emission for a particular increment of time.
…The .delay(), .interval() operators uses a Scheduler by default which is why we see it executing on a different thread RxComputationThreadPool-1 which actually means it's running the operators and the subscribe operations on another thread and so the test method will terminate before we see the text from the log unless we wait for the completion of the stream. This is the role of the CountdownLatch.
Periodically emits a number starting from 0 and then increasing the value on each emission.
…Takes an initial value and a function(accumulator, currentValue). It goes through the events sequence and combines the current event value with the previous result(accumulator) emitting downstream the function's result for each event(the initial value is used for the first event)
…reduce operator acts like the scan operator but it only passes downstream the final result (doesn't pass the intermediate results downstream) so the subscriber receives just one event
…collect operator acts similar to the reduce operator, but while the reduce operator uses a reduce function which returns a value, the collect operator takes a container supplier and a function which doesn't return anything(a consumer). The mutable container is passed for every event and thus you get a chance to modify it in this collect consumer function.
…because the usecase to store to a List container is so common, there is a .toList() operator that is just a collector adding to a List.
An easy way to switch from a blocking method to a reactive Single/Flowable is to use .defer(() -> blockingOp()).
Simply using Flowable.just(blockingOp()) would still block, as Java needs to resolve the parameter when invoking Flux.just(param) method, so blockingOp() method would still be invoked(and block).
//NOT OK
Flowable flowableBlocked = Flowable.just((blockingOp())); //blocks on this lineIn order to get around this problem, we can use Flowable.defer(() -> blockingOp()) and wrap the blockingOp() call inside a lambda which will be invoked lazy at subscribe time.
Flowable stream = Flowable.defer(() -> Flowable.just(blockingOperation()));
stream.subscribe(val -> log.info("Val " + val)); //only now the code inside defer() is executedOperators for working with multiple streams Code at Part03MergingStreams.java
Zip operator operates sort of like a zipper in the sense that it takes an event from one stream and waits for an event from another other stream. Once an event for the other stream arrives, it uses the zip function to merge the two events.
This is an useful scenario when for example you want to make requests to remote services in parallel and wa
暂无开放 Issues,或尚未同步最近议题。