整理自油管上一个RxJava的视频:https://www.youtube.com/watch?v=XLH2v9deew0&t=1s
Tools for async work:
AsyncTask, Future, EventBus, Observable
RX = Observables + LINQ + Schedulers
1) Represent asynchronous data streams
2) Query and combine streams with operators
3) Manage concurrency
Observables
-
Streams of data
-
Pull based
-
Create, store, pass around
-
Abstract away threading, syncronization, concurrency
和工厂类比
-
Raw material == creation
-
Conveyor belts == operators/transforms
-
End product == output
-
Put data in
-
Get data out
What do we need?
-
Give me the next piece of data
-
Is there any more data left to process
-
Did any errors happen that I should know about?
How do we get those?
-
onNext
-
onComplete
-
onError
What does this stream look like? s.onNext(2); s.onNext(3); s.onComplete();
-→2-→3-→x
ON ERROR
-
If an error occurs in a stream, it will cease to output any more data
-
Errors are handled in one place
Observables really shine when you need to compose several streams of asynchronous data.
OPERATORS
-
combining data
-
filtering/reducing data
-
transforming data
Start Listening
-
without Subscribe, nothing happens
Subscribe basics
-
Subscribers can take different numbers of functions
-
Best practice: always pass an onError func
-
Use subscribeOn and observeOn to assign to threads
-
.subscribe will return a Subscription
-
Unsurprisingly, you can unsubscribe from it.
Subscribe On
-
Declare only once
-
Defaults to thread on which observable is created
-
Obs will always tick off execution on this thread, no matter where it’s decleard
Observe On
-
Declare as many times as needed
-
Affects all operators downstream
Rx & Android
-
Bind to clicks and filter clicks for a given area
-
Flatmap cache hit with network call
-
Handle auth flow with a single stream