Reactive Programming with RxJava-Chapter4:Applying Reactive Programming to Existing Application(2)

Replacing Callbacks with Streams

The easiest way to convert from a push,callback-based API to Observable is to use *Subject*s
Do remember to take care of resource cleanup and proper error.

Polling Periodically for Changes

distinctUntilChanged.key

Observable
        .interval(10,TimeUnit.MILLISECONDS)
        .map(x -> getOrderBookLength())
        .distinctUntilChanged()

distinct

Observable<Item> observeNewItems(){
    return Observable
            .interval(1,TimeUnit.SECONDS)
            .flatMapIterable(x -> query())
            .distinct();
}

Multithreading in RxJava

What Is a Scheduler

Schedulers are used together with subscribeOn() and observeOn() operators as well as when creating certain types of Observables.A scheduler only creates instances of Worker*s that are responsible for scheduling and runnning code.When RxJava needs to scheduler some code it first aseks *Scheduler to provide a Worker and uses the latter to schedule subsequent tasks

1、Schedulers.newThread

This scheduler can be useful only when tasks are coarse-grained:it takes a lot of time ot complete but there are very few of them,so that threads are unlikely to be reused at all.

Schedulers.io

Every time a new Worker is requested,either a new thread is started (and later kept idle for some time) or the idle one is reused.
Consider using this scheduler for I/O bound tasks which require very little CPU resources.

Schedulers.computation()

You should use a computation scheduler when tasks are entirely CPU-bound;that is,they require computational power and have no blocking code (reading from disk,network,sleeping,waiting for lock,etc)

Schedulers.from(Executor executor)

Creating schedulers from Executor that we consciously configured is advised for projects dealing with high load.However because RxJava has no control voer independently created threads in an Executor,it cannot pin threads (that is ,try to keep work of the same task on the same thread ot improve cache locality).This Scheduler barely makes sure a single Scheduler.Worker processes events sequentially.

Schedulers.immediate()

Using it is pointless unless some part of your API requires providing a scheduler,whereas you are absolutely fine with default behavior of Observable,not involving any threading at all.In general,avoid this scheduler,it blocks the calling thread and is of limited use.

Schedulers.trampoline()

As opposed to immediate(),the upcoming task is executed when all previously scheduled tasks complete.

Sechedulers.test()

Declarative Subscription with subscribeOn()

Observable s tend to be backed by other concurrency mechanisms like event loops or custom threads,so Rx lets you take full control than imposing any convention.

Attention
- Observable should be responsible only for production logic.
- Observable is lazy but also immutable,in the sense that subsrcibeOn() affects only downstream subsccribers

subscribeOn() Concurrency and Behavior

If you are desiging an API and you use subscribeOn() internally,the client code has no way of overriding the Scheduler of your choice

RxJava creates a single Worker instance for the entrie pipeline,mostly ot guarantee sequential processing of events

Observable<BigDecimal> totalPrice = Observable
        .just("bread","butter","milk","tomato","cheese")
        .flatMap(prod ->
                rxGroceries
                        .purchase(prod,1)
                        .subscribeOn(schedulerA))
        .reduce(BigDecimal::add)
        .single();

Batching Requests Using groupBy()

Observable<BigDecimal> totalPrice = Observable
    .just("bread","butter","egg","milk","tomato",)
        "cheese","tomato","egg","egg")
    .groupBy(prod -> prod)
    .flatMap(grouped -> grouped
        .count()
        .map(quantity -> {
            String productName = grouped.getKey();
            return Pair.of(productName.quantity);
        }))
    .flatMap(order ->store
        .purchase(order.getKey(),order.getValue())
        .subscribeOn(schedulerA))
    .reduce(BigDecimal::add)
    .single()

Declarative Concurrency with observeOn()

Attention
Remember,everything below observeOn() is run within the supplied Scheduler,of course until another observeOn() is encountered.Additionally subscribeOn() can occur anywhere between Observable and subsribe(),but this is time it only affects operators down to the first observeOn().

Other Uses for Schedulers

There are numerous operators that by default use some Scheduler.Typically,Schedulers.computation is used if none is supplied–JavaDoc always makes it clear.

最后,安利一款自己写的基于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、付费专栏及课程。

余额充值