RxJava Introduction

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_sdn/article/details/84589553

整理自油管上一个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

  1. Put data in

  2. Get data out

What do we need?

  1. Give me the next piece of data

  2. Is there any more data left to process

  3. Did any errors happen that I should know about?

How do we get those?

  1. onNext

  2. onComplete

  3. 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

  1. Bind to clicks and filter clicks for a given area

  2. Flatmap cache hit with network call

  3. Handle auth flow with a single stream

猜你喜欢

转载自blog.csdn.net/M_sdn/article/details/84589553
今日推荐