Reactive Programming with RxJava-Chapter6:Flow Control and Backpressure(2)

Backpressure

Attention
Backpressure is a simple protocol that allows the consumer to request how much data it can consume at a time,effectively providing a feedback channel to a producer.Producers receive requests from consumers,avoiding message overflow.Of course,this algorithm can work only with producers that are capable of throttling themselves;for example,when they are backed by static collection or source that can be pulled from something like Iterator.When the producer has no control over the frequency of data it produces (the source is external or hot),backpressure can not help much.

Backpressure in RxJava

Built-in Backpressure

  • observableOn()
  • zip()

Producers and Missing Backpressure

Attention
Observable produced by range() (and many other built-in operators) no longer pushes data eagerly to Subscribers.Instead,it wakes up and reacts on data requests (request(N) invocations with Subscriber) and only then produces events.Also,it makes sure not to produce more than was requested.

The onBackpressure*() family of methods is used to bridge between operators and subscribers requesting backpressure and Observables that are not supporting it.However,it is better to either use or create sources that support it natively.

onBackpressureBuffer()
Reactive Programming with RxJava-Chapter6:Flow Control and Backpressure(2)_第1张图片

onBackpressureDrop()
Reactive Programming with RxJava-Chapter6:Flow Control and Backpressure(2)_第2张图片

onBackpressureLatest()
Reactive Programming with RxJava-Chapter6:Flow Control and Backpressure(2)_第3张图片

Honoring the Requested Amount of Data

There are many ways to construct an Observable that supports downstream backpressure request.

  1. Use built-in factory methods like range() or from(Iterable)
  2. Producer
  3. SyncOnSubscriber/AsyncOnSubscriber

Tip
When creating your Observables,think about correctly handing the backpressure request.After all,you have no control over the throughput of Subscribers.Another technique is to avoid the heavyweight work in Subscriber,instead off-loading it to flatMap().

//For example:
//Good!
source
    .flatMap(this::store)
    .subscribe(uuid -> log.debug("Stored: {}",uuid));

//Bad!
source.subscribe(this::store);

最后,安利一款自己写的基于MVP的Android开发框架
https://github.com/sxenon/Pure
欢迎大家拍砖,如果觉得好,麻烦多多star

你可能感兴趣的:(RxJava,1.x,学习笔记)