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
Observable
.interval(10,TimeUnit.MILLISECONDS)
.map(x -> getOrderBookLength())
.distinctUntilChanged()
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