Rxjava基本用法總結

2021-07-29 05:31:40 字數 2856 閱讀 4916

參考:

扔物線大神

1. observable

被觀察者:有兩種建立方式

observable observable = observable.create(new observableonsubscribe() 

});

observable observable1 = observable.just("hello", "hi", "aloha");

// 將會依次呼叫:

// onnext("hello");

// onnext("hi");

// onnext("aloha");

// oncompleted();

2.observer,subscriber

觀察者有三種建立方式:

observerobserver= new observer() 

@override

public

void

onnext(string value)

@override

public

void

onerror(throwable e)

@override

public

void

oncomplete()

};

//對observer進行了功能的擴充套件,同時也是觀察者

subscribersubscriber = new subscriber()

@override

public

void

onnext(string s)

@override

public

void

onerror(throwable t)

@override

public

void

oncomplete()

};

action1onnextaction = new action1() 

};action1onerroraction = new action1()

};action0 oncompletedaction = new action0()

};// 自動建立 subscriber ,並使用 onnextaction 來定義 onnext()

observable.subscribe(onnextaction);

// 自動建立 subscriber ,並使用 onnextaction 和 onerroraction 來定義 onnext() 和 onerror()

observable.subscribe(onnextaction, onerroraction);

// 自動建立 subscriber ,並使用 onnextaction、 onerroraction 和 oncompletedaction 來定義 onnext()、 onerror() 和 oncompleted()

observable.subscribe(onnextaction, onerroraction, oncompletedaction);

3. 執行緒控制 —— scheduler

schedulers.immediate(): 直接在當前執行緒執行,相當於不指定執行緒。這是預設的 scheduler。

schedulers.newthread(): 總是啟用新執行緒,並在新執行緒執行操作。

schedulers.io(): i/o 操作(讀寫檔案、讀寫資料庫、網路資訊互動等)所使用的 scheduler。行為模式和 newthread() 差不多,區別在於 io() 的內部實現是是用乙個無數量上限的執行緒池,可以重用空閒的執行緒,因此多數情況下 io() 比 newthread() 更有效率。不要把計算工作放在 io() 中,可以避免建立不必要的執行緒。

schedulers.computation(): 計算所使用的 scheduler。這個計算指的是 cpu 密集型計算,即不會被 i/o 等操作限制效能的操作,例如圖形的計算。這個 scheduler 使用的固定的執行緒池,大小為 cpu 核數。不要把 i/o 操作放在 computation() 中,否則 i/o 操作的等待時間會浪費 cpu。

另外, android 還有乙個專用的 androidschedulers.mainthread(),它指定的操作將在 android 主線程執行。

observable.create(onsubscribe)

.subscribeon(schedulers.io())

.doonsubscribe(new action0()

}).observeon(schedulers.newthread())

.map(mapoperator) // 新執行緒,由 observeon() 指定

.subscribeon(androidschedulers.mainthread()) // 指定主線程

.observeon(androidschedulers.mainthread())

.subscribe(subscriber);

4.map

observable.just("images/logo.png") // 輸入型別 string

.map(new func1()

}).subscribe(new action1()

});

RxJava基本使用2

map變換操作符 將傳送的資料按指定的函式去變化 例子 observable.create new observableonsubscribe map new function subscribe new consumer flatmap變換操作符 將傳送的事件分解成多個事件後發送回接收方 注意 f...

STL基本用法總結

1 vector的基本用法 include 1 定義 vectors 定義乙個空的 vector 物件,儲存的是 int型別的元素。vectors n 定義乙個含有n個 int元素的 vector 物件。2 基本操作 s i 直接以下標方式訪問容器中的元素。s.front 返回首元素。s.back ...

JQuery基本用法總結

1.css選擇器 documnet css 選擇整個文件物件 myid 選擇id myid的元素 div myclass 選擇class為myclass的div元素 2.jquery特有的表示式 a first 選擇網頁中的第乙個a元素 tr odd 選擇 的奇數行 div visible 選擇可見...