SlideShare a Scribd company logo
1 of 120
Beginning RxJava
in Android
初心者的RxJava _by Kelly Hong
概要
- RxJava 介紹與簡單使用。
- Observable 相關運作流程。
- 使用 RxJava 與 Retrofit。(in Android)
3
導入專案
4
*由於搭配其他 lib 使用的是 RxJava2
RxAndroid can be understood as an extension to RxJava
所以什麼是RxJava?
5
Thread怎麼進行切換?
為什麼是Reactive?
Data flow要怎麼流?
為什麼要用它?
使用它有什麼好處?
什麼是Observable?
什麼是Back-pressure?
Thread要怎麼選?
為什麼還有Flowable?
什麼是Emitter(發射器)?
文件的時間流解釋圖要怎麼看?
Mapping是要映射什麼?
要怎麼延遲?
為什麼可以防手抖?
它就像是在挖渠道
6
我覺得
官方定義
RxJava is a Java VM implementation of Reactive Extensions: a library for composing
asynchronous and event-based programs by using observable sequences.
It extends the observer pattern to support sequences of data/events and adds
operators that allow you to compose sequences together declaratively while
abstracting away concerns about things like low-level threading, synchronization,
thread-safety and concurrent data structures.
7
“
”
兩個核心概念
- 響應式程式設計: (Reactive Programming)
從關心資料與事件變動去撰寫
- 基於事件的程式設計: (Event driven programming)
將觸發事件的串流為開頭去撰寫
8
9
如何觀測變化?
主題
可以被觀測
(訂閱)
* 引用聖經版的架構圖
當主題變動
會通知觀測者
(主題會擁有觀
測者的參照)
Detach(Observer)
10
觀測者模式(Observer Pattern)
* 主題已有A,B兩
個具體觀測者
* 引用聖經版的時序圖
基本角色
- Observer :
觀測者,接收發射器的資料
- Observable :
能被觀測的事件流,可以發射資料,
被訂閱(Subscribe)時才會驅動。
11
基本概念
12
Client
Emitter
Upstream
Downstream
Source
Consumer
想像示意圖
13
Source
Consumer
基礎類別(Reactive base class)
14
背壓(Back-Pressure)
存在現象: 當在異步環境下,上游資料來源過快,使得下游觀測者無法消耗
- Flowable:
能夠採取 1.使用buffer來暫存未被消耗的變動事件
2. 忽略該事件
15
操作符(Operation)
- 創建 (Creating) : 製造源頭
Create, Defer, Empty/Never/Throw, From, Interval, Just, Range, Repeat, Start, Timer
- 轉換 (Transforming) : 中間站
Buffer, FlatMap, GroupBy, Map, Scan, Window
- 篩選 (Filtering) :
Debounce, Distinct, ElementAt, Filter, First, IgnoreElements, Last, Sample, Skip,
SkipLast, Take, TakeLast
- 組合 (Combining) :
And/Then/When, CombineLatest, Join, Merge, StartWith, Switch, Zip
16
想像示意圖
17
Creating
Filtering
Combining
Transforming
文件例圖介紹
18
Error
Event
如何指定執行緒?
- subscribeOn:
指定資料來源於哪個執行緒類型上執行
- observeOn:
指定在這之後的下游於哪個執行緒類型上執行
19
Schedulers
Basic :
- io()
- newThread()
- computation()
- single()
- trampoline()
- from(e)
20
In Android :
- mainThread()
- from(Looper)
想像示意圖
21
Observable 相關流程
22
渠道實際工程
將語句拆開
23
Client
Subscription
time
Assembly
time
如何製作渠道?
24
Observable.java
Client
- 關於RxJavaPlugins :
它提供了一些額外的功能,
並允許你能使用掛鉤的方式插入原本的生命週期。
這裡我們不多作探討。
補充說明RxJava Hooks
25
更多參考
26
實際類別圖
如何製作渠道?
27
Client
如何製作渠道?
28
Observable.java
Client
29
實際類別圖
Schedulers.io()
如何製作渠道?
30
Client
如何製作渠道?
31
Observable.java
Client
use default size
32
實際類別圖
AndroidSchedulers.mainThread()
如何製作渠道?
33
Client
34
實際類別圖
如何製作渠道?
35
Client
如何開通渠道?
36
不用Consumer
也可以自己實作
Observer
Client
Observable.java
37
實際類別圖
如何開通渠道?
38
Observable.java
如何開通渠道?
39
Observable.java
callBackTreadObservable
40
ObservableOnSubscribe
ObservableCreate
ObservableSubscribeOn
ObservableObserveOn
*外面知道裡面
裡面不知道外面
如何開通渠道?
41
ObservableObserveOn.java
42
實際類別圖
AndroidSchedulers.mainThread()
如何開通渠道?
43
Observable.java
如何開通渠道?
44
ObservableSubscribeOn.java
Consumer
Observer
45
LambdaObserver
ObserveOnObserver
SubscribeOnObserver
*裡面->外面 subscribe(source/observable)
外面->裡面 onSubscribe(disposable)
如何開通渠道?
46
ObservableSubscribeOn.java
實際類別圖
47
Queue
Disposable<T>
Queue
Fuseable<T>
AtomicInteger
如何開通渠道?
48
ObservableObserveOn
.ObserveOnObserver
如何開通渠道?
49
DisposableHelper.jav
a
如何開通渠道?
50
LambdaObserver.java
51
實際類別圖
AtomicReference
52
AtomicReference.java
保證對象在共享變量的原子操作
如何開通渠道?
53
LambdaObserver.java
如何開通渠道?
54
DisposableHelper.jav
a
如何開通渠道?
55
LambdaObserver.java
是空實作!
如何開通渠道?
56
ObservableSubscribeOn.java
實際類別圖
57
Queue
Disposable<T>
Queue
Fuseable<T>
AtomicInteger
如何開通渠道?
58
Scheduler.java
Schedulers.io()
如何開通渠道?
59
IoScheduler.
EventLoopWorker
60
實際類別圖
setDiaposable
如何開通渠道?
61
ObservableSubscribeOn.
SubscribeTask
Client
如何開通渠道?
62
Observable.java
如何開通渠道?
63
ObservableCreate.java
ObservableSubscribeOn.
SubscribeOnObserver
如何開通渠道?
64
ObservableCreate.java
Client
65
實際類別圖
如何發射事件?
66
Client
ObservableCreate.
CreateEmitter
invoke
如何發射事件?
67
ObservableObserveOn
.ObserveOnObserver
done==true onNext剛被調度完,
onError或者onCompele被調用
ObservableSubscribeOn.
SubscribeOnObserver
如何發射事件?
68
ObservableObserveOn
.ObserveOnObserver
AndroidSchedulers.mainThread()
HandlerScheduler.HandlerWorker
如何發射事件?
69
ObservableObserveOn
.ObserveOnObserver
輸出端是否已消融
默認為否
在onSubscribe時檢查
如何發射事件?
70
ObservableObserveOn
.ObserveOnObserver
71
OnNext
Schedule
onNext
Run
onNext
acceptonNext
onNext
如何註銷串流?
註銷(Disposable) :
當觀測者不在需要觀測 Observable ,就需要進行註銷,以免未來發生memory leak
72
如何註銷串流?
CompositeDisposable :
當有多個觀測者需要被維護時,
利用CompositeDisposable,可以進行統一管理。
● compositeDisposable.clear()
73
如何註銷串流?
74
ObservableCreate.
CreateEmitter
Client
invoke
如何註銷串流?
75
ObservableObserveOn
.ObserveOnObserver
ObservableSubscribeOn.
SubscribeOnObserver
如何註銷串流?
76
ObservableObserveOn
.ObserveOnObserver
如何註銷串流?
77
ObservableObserveOn
.ObserveOnObserver
如何註銷串流?
78
LambdaObserver.java
如何註銷串流?
79
HandlerScheduler.HandlerWorker
如何註銷串流?
80
ObservableCreate.
CreateEmitter
DisposableHelper.jav
a
81
OnComplete
onComplete
onComplete
onComplete
Dispose
onComplete
Dispose
82
OnError
onError
onError
onError
Dispose
onError
Dispose
queue.clear()
83
dispose
Dispose
Dispose
Dispose
Dispose
Dispose
Dispose
DisposeTask
總結
84
- 上游事件發送者(Emmiter)將控管事件源頭
- 明白執行緒的切換
- 明白內部的相依關係
- 下遊進入 onComplete/onError 會堵住整條流動
加入Retrofit
85
最後
設置
86
Retorfit簡易使用
87
Retorfit簡易使用
88
中間發生什麼了?
89
Retrofit.java
90
實際類別圖
中間發生什麼了?
91
Retrofit.java
92
實際類別圖
93
實際類別圖
parseAnnotations
中間發生什麼了?
94
HttpServiceMethod.java
95
實際類別圖
callAdapter
中間發生什麼了?
96
Retrofit.java
97
實際類別圖
中間發生什麼了?
98
RxJava2CallAdapterFactory.java
99
實際類別圖
return
return
invoke
中間發生什麼了?
100
HttpServiceMethod.java
101
實際類別圖
中間發生什麼了?
102
RxJava2CallAdapter.java
103
實際類別圖
RxJava2CallAdapterFactory
104
- create()
- createAsync()
isAsync = true
- createWithScheduler(Scheduler scheduler)
specify scheduler
105
實際類別圖
return
中間發生什麼了?
106
CallExecuteObservable.java
107
實際類別圖
範例事件
108
範例事件
109
Retorfit簡易使用
110
想像示意圖
111
發生錯誤
112
發生錯誤
113
想像示意圖
114
讓錯誤繼續
115
想像示意圖
116
錯誤重試
117
總結優點
- Highly interactive experience
- Replace the callbck hell
- Thread use is simple
- Flexible
118
Reference
RxJava & RxAndroid:
https://github.com/ReactiveX/RxAndroid
https://github.com/ReactiveX/RxJava
ReactiveX/RxJava Doc(chinese):
https://mcxiaoke.gitbooks.io/rxdocs/content/
Retorfit Adapter:
https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2
Reactive-Programming-With-RxJava:
https://github.com/MohammadSianaki/Reactive-Programming-With-RxJava
ReactiveX: The observer pattern done right:
http://delphi.pl/zlot/zlot2017/prezentacje/ReactiveX_SG.pdf
119
那麼謝謝大家
該出發去挖渠道了!_

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Beginning RxJava in Android

Editor's Notes

  1. 我是這個議程的講者 我叫Kelly Hong 這次的分享主題是面向初心者的RxJava
  2. 大綱的部分主要分成三個 在了解如何使用之前 我會先以概念下去循序漸進的講解
  3. 要使用一個工具前我們需要先建立好環境 // Because RxAndroid releases are few and far between, it is recommended you also // explicitly depend on RxJava's latest version for bug fixes and new features.// (see https://github.com/ReactiveX/RxJava/releases for latest 2.x.x version) RxAndroid is specific to Android Platform with few added classes on top of RxJava. 多了執行緒
  4. 或打造生產線
  5. 先讓我們一起來看它官方的定義 簡單說它是為了實踐響應式程式設計這個概念的工具 它幫你解決了要在同的事件下指定不同執行緒的部分 像這裡提到同步異步以及執行緒安全... 到這裡大家或許能有一些模糊的想像了
  6. 進一步放重點 這邊有兩個主要的思考 我們將每個 針對資料去響應變化 也就是說我們 關心事件來源 並 關心它的變化 可以是使用者觸發的點擊事件 可以是API的回覆 可以是從disk內DB取得資料 而上述一直說到的變化 RX採用觀察者模式去做綁定 原本我們以前在寫可能是用簡單的callback 串流指的是從資料來源的一系列循序的物件 這些物件支援聚合(aggregate)類型的操作
  7. 接著我們來介紹一下觀測者模式 觀測者可以觀測主題,他們的關係式多對多 也就是一個觀測者可以觀察多個主題 而主題可以同時被多位關測者觀察 當主題變動時,會通知觀測者 觀測者再進行相應的變化
  8. Observable: Observable is a data stream that do some work and emits data. Observer: Observer is the counter part of Observable. It receives the data emitted by Observable.
  9. Subscription: The bonding between Observable and Observer is called as Subscription. There can be multiple Observers subscribed to a single Observable.
  10. 衍生出來解決上述問題
  11. Operator / Transformation: Operators modifies the data emitted by Observable before an observer receives them.
  12. 一般的操作是沒有切換執行緒的 Schedulers: Schedulers decides the thread on which Observable should emit the data and on which Observer should receives the data i.e background thread, main thread etc.,
  13. Schedulers.io() – 主要是處理非密集型的操作,像是遠端要求,像本地端讀取資料 ,資料庫操作等。它支援thread-pool,所以可以重複使用已經創建的執行緒,並且會移除持續一分鐘沒有工作的執行緒,但是它的執行緒創建是沒有上限的,這可能會在大量創建實兆呈效能上的問題。 AndroidSchedulers.mainThread() – 處理畫面更心上的操作,也就是android UI thread Schedulers.newThread() – 會為你要執行的task創建一個新的執行緒,適合非常長時間的操作,而且該執行緒是不會被重複利用的。 Schedulers.computation() – 它的thread-pool的執行緒上限會依照可執行核心數去創建,適合大量的運算,像是bitmap processing。 Schedulers.single() – 讓所有task依序在同一個執行緒執行,適合有順序需求的情況。 Schedulers.trampoline() – 讓所有的task依你給予的順序(FIFO)執行於current thread,可以用於unit test。 Schedulers.from() – 由自己定義的 executor 來創建. Schedulers.immediate() – This scheduler executes the the task immediately in synchronous way by blocking the main thread.
  14. 先從創造開始 到如何訂閱綁定觀察者跟Observable的關係 最後再看發射器是怎麼運作的
  15. atomic https://blog.csdn.net/zxc123e/article/details/52057289
  16. Verifies that current is null, next is not null 預設的upstream = null 執行第一次才把parent 設給upstream
  17. Verifies that current is null, next is not null next.get() == null => true
  18. setOnce 會將d設給this,操作執行成功回傳true 這邊的操作是去檢查this==null 將d:=this this != null 直接進行dispose
  19. provides an object reference variable which can be read and written atomically. By atomic is meant that multiple threads attempting to change the same AtomicReference (e.g. with a compare-and-swap operation) will not make the AtomicReference end up in an inconsistent state. AtomicReference even has an advanced compareAndSet() method which lets you compare the reference to an expected value (reference) and if they are equal, set a new reference inside the AtomicReference object.
  20. setOnce 會將d設給this,操作執行成功回傳true 這邊的操作是去檢查this==null 將d:=this this != null 直接進行dispose
  21. 可以看到 SubscribeOnObserver 和 LamdaObserver 與它繼承實作的類是一樣的 他們一樣擁有對diposable進行執行緒安全處理的原子性 而ObserverOnObserver則擁有queue的特性 且它本身自己有實作Runnable
  22. 可以驗證了我們的observable emitter發射是運行於io thread 重複設定並不會有效過 只會被最上源的subscribon覆蓋 若是沒有指定observeron將會把所有的運行都run 在io thread
  23. oncomplete single …
  24. 或打造生產線
  25. /** * Returns an instance which creates asynchronous observables. Applying * {@link Observable#subscribeOn} has no effect on stream types created by this factory. */ /** * Returns an instance which creates synchronous observables that * {@linkplain Observable#subscribeOn(Scheduler) subscribe on} {@code scheduler} by default. */
  26. Catch操作符拦截原始Observable的onError通知,将它替换为其它的数据项或数据序列,让产生的Observable能够正常终止或者根本不终止。 在某些ReactiveX的实现中,有一个叫onErrorResumeNext的操作符,它的行为与Catch相似。 RxJava将Catch实现为三个不同的操作符: onErrorReturn 让Observable遇到错误时发射一个特殊的项并且正常终止。 onErrorResumeNext 让Observable在遇到错误时开始发射第二个Observable的数据序列。 onExceptionResumeNext 让Observable在遇到错误时继续发射后面的数据项。
  27. "Why should I consider adopting RP?" Reactive Programming raises the level of abstraction of your code so you can focus on the interdependence of events that define the business logic, rather than having to constantly fiddle with a large amount of implementation details. Code in RP will likely be more concise. The benefit is more evident in modern webapps and mobile apps that are highly interactive with a multitude of UI events related to data events. 10 years ago, interaction with web pages was basically about submitting a long form to the backend and performing simple rendering to the frontend. Apps have evolved to be more real-time: modifying a single form field can automatically trigger a save to the backend, "likes" to some content can be reflected in real time to other connected users, and so forth. Apps nowadays have an abundancy of real-time events of every kind that enable a highly interactive experience to the user. We need tools for properly dealing with that, and Reactive Programming is an answer.