The role of Rxjava

Observer model

  • Many to one, multiple observers, one observed, the observer has a high degree of data sensitivity to the observed and can make changes accordingly.

UML class diagrams

  • Observerable of the observed objectnotifyObservers()Will traverse each observer in turn and call itupdate().

The observer mode uses the scene

The use of Rxjava

  1. Create observed -3 ways
    • withcreateMethods. Note that Subscriber is the Observer
    • justmethods
    • frommethods
  2. Create observer
  • onNext()In the traditional observer modelonupdate().
  1. To subscribe to
  • callsubscribeObservables.OnSubscribe by defaultcallMethod to complete event consumption.

Rxjava source

— Go to class Subscriber

  • SubscriptionList holds all subscription events for the Subscriber/Observer, and the events will be deleted from the List when the subscription is unsubscribed. – to enterobservable.subscribe(observer)
  • Internally, Subscriber is wrapped as SafeSubscriber and implementedonCompleted().onError().onNext()Methods.
  • The final callcall(subscriber)Complete the subscription.

Rxjava operator

Map — Mapping/event transformation

  • Func1<String, Bitmap> is an interface that converts a String image path to a Bitmap. The Map operator creates a new Observable and then chain-calls itsubscribe.

flatMap

  • Func1

    converts String to Observable.
    ,>

Rxjava thread control

Schedulers

  • Schedulers.immediate(): Executes on the current thread without switching threads.
  • Schedulers.newthread (): New threads are always enabled to perform operations.
  • Schedulers.io(): Performs I/O operations, such as reading and writing files, and network information interaction (commonly used).
  • Schedulers.computation(): Performs CPU-intensive calculations.
  • AndroidSchedulers. MainThread () : switch the main thread execution (common).

How do I do thread control

  1. subscribeOn()Observable: specifies the thread in which the observer is subscribed, which is the thread in which Observable.OnSubscribe is activated.
  2. observeOn(): The thread where the event is consumed.

Example of thread control

  • observeOn(..)Specifies the thread on which subsequent operations are performed, and can be called multiple times.
  • subscribeOn(..)Can be inobserveOn(..)Can be invoked before or after only once.

SubscribeOn method

subscribeOnandobserverOn

  • subscribeOnandobserverOnBoth operate on threads through the Executor pool.