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()
onBackpressureBuffer()

onBackpressureDrop()
onBackpressureDrop()

onBackpressureLatest()
onBackpressureLatest()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值