在上一節中,咱們討論了observable的工做原理和建立過程,那麼在這一節中,咱們來介紹observable類所具備的一系列方法,經過這些方法,咱們能夠更加靈活地使用observable變量。this
Operators的使用 Operators是observable類擁有的一系列public method,本節咱們經過實際代碼來演練一些經常使用的operator,並看看他們輸出的結果。code
1.maporm
map方法的做用是對每一個observable對象發出的值,根據必定的規則進行映射。以下:對象
source_from = Observable.from('123').map(x => x + 's ');
能夠獲得結果rxjs
相似的還有mapTo方法,能夠將發出的值映射爲固定值。圖片
2.zipip
zip方法能夠將兩個observable序列合併爲一個observable序列。以下文檔
source_from = Observable.from('123'); source_interval = Observable.interval(1000); source_zip = this.source_from.zip(this.source_interval, (x, y) => x);
經過以上方法,就能夠將interval和from方法進行結合,一、二、3會在相隔1s後相繼輸出,再輸出complete。it
3.scanio
scan方法相似於reduce方法,對發出的值進行accumulation的處理。以下:
source_from = Observable.from('Andrew'); source_interval = Observable.interval(1000); source_zip = this.source_from.zip(this.source_interval, (x, y) => x); source_scan = this.source_zip.scan((origin, next) => origin + next, 's');
能夠獲得這樣的輸出結果:
4.filter
filter方法能夠對發出的值進行過濾操做,並制定過濾條件。以下:
source_from = Observable.from([1, 2, 3, 4, 5, 6, 7]); source_interval = Observable.interval(1000); source_zip = this.source_from.zip(this.source_interval, (x, y) => x); source_filter = this.source_zip.filter((x) => x % 2 !== 0);
則能夠看到以下的輸出:
5.take
take方法能夠制定觀察者接收到的值的數量,在達到指定數量後,則會調用觀察者的complete方法。
source_from = Observable.from([1, 2, 3, 4, 5, 6, 7]); source_interval = Observable.interval(1000); source_zip = this.source_from.zip(this.source_interval, (x, y) => x); source_filter = this.source_zip.take(3);
則能夠獲得以下的輸出:
6.distinct
distinct能夠對一系列發送的值進行去重操做。
source_from = Observable.from([1, 2, 2, 6, 5, 6, 7, 4, 4]); source_interval = Observable.interval(1000); source_zip = this.source_from.zip(this.source_interval, (x, y) => x); source_distinct = this.source_zip.distinct();
那麼能夠獲得這樣的輸出:
到目前爲止,咱們僅僅介紹了不少operator中的6個,事實上,對於不一樣情形,operator能夠分爲creation, filter, combination, transformation等等的功能,建議你根據本身的需求去查閱rxjs的官方文檔,進行合適的使用。