SwiftUI 與 Combine(二)

操作符

本文將介紹Combine中的各類(lèi)運(yùn)算符,這些運(yùn)算符不要求你能夠立即掌握,只要記得有某種運(yùn)算符具有某種作用,在實(shí)際編程中可以將本文作為文檔查詢(xún)(ps:作者在使用RXSwift時(shí)也會(huì)經(jīng)常查詢(xún)某些不常用的操作符)
正如Swift標(biāo)準(zhǔn)庫(kù)中對(duì)數(shù)組的操作符(map、filter、zip...)一樣,publisher也有著變形、篩選、鏈接等等操作符

collect

本操作符將單個(gè)元素緩存到集合中(可以指定緩存?zhèn)€數(shù),滿(mǎn)足個(gè)數(shù)或者收到完成事件后),然后發(fā)送集合


15785495862104.jpg
var subscriptions = Set<AnyCancellable>()
var subscriptions = Set<AnyCancellable>()
example(of: "collect") {
    ["A", "B", "C", "D", "E"].publisher
//        .collect()
//        .collect(2)
        .sink(receiveCompletion: { print($0) },
              receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: collect ———
A
B
C
D
E
finished

// 打開(kāi).collect()注釋
——— Example of: collect ———
["A", "B", "C", "D", "E"]
finished

// 注釋掉.collect()打開(kāi).collect(2)注釋
——— Example of: collect ———
["A", "B"]
["C", "D"]
["E"]
finished
*/

使用.collect和其他沒(méi)有指定個(gè)數(shù)或緩存大小的操作符時(shí),注意他們講使用沒(méi)有內(nèi)存大小限制的緩存區(qū)存儲(chǔ)收到的元素。注意內(nèi)存溢出

map(_:)

和Swift標(biāo)準(zhǔn)庫(kù)中集合的Map類(lèi)似,使用函數(shù)、閉包、或者keyPath來(lái)轉(zhuǎn)變值

/// 將數(shù)字轉(zhuǎn)換成對(duì)應(yīng)的ASCll值的字符,無(wú)法轉(zhuǎn)換時(shí)返回空字符
func numToString(num: Int) -> String {
    .init(Character(Unicode.Scalar(num) ?? "\0"))
}
example(of: "map") {
    (65...67)
        .publisher
        .map(numToString(num:))
        .print()
        .map(\.localizedLowercase)
        .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: map ———
receive subscription: (["A", "B", "C", "D", "E"])
request unlimited
receive value: (A)
a
receive value: (B)
b
receive value: (C)
c
receive finished
finished
*/

print

打印接受到的值或者完成事件,通常用在調(diào)試的時(shí)候

tryMap

包括map在內(nèi)的幾個(gè)操作符都有一個(gè)對(duì)應(yīng)的try操作符,該操作符將接受可能引發(fā)錯(cuò)誤的閉包。如果有錯(cuò)誤拋出,它將發(fā)送錯(cuò)誤完成事件

example(of: "tryMap") {
    let publisher = PassthroughSubject<String, Never>()

    publisher
        .tryMap { try JSONSerialization.jsonObject(with: $0.data(using: .utf8)!, options: .allowFragments) }
        .sink(receiveCompletion: { print($0) },
              receiveValue: { print($0) })
        .store(in: &subscriptions)

    publisher.send(#"{"name":"DKJone"}"#)
    publisher.send("not a JSON")
}

/* 輸出
——— Example of: tryMap ———
{
    name = DKJone;
}
failure(Error Domain=NSCocoaErrorDomain Code=3840 ...."})
*/

此處使用的#""#為原始字符串更多內(nèi)容查看Swift5新特性 & XCode 10.2更新

flatMap

在swift標(biāo)準(zhǔn)庫(kù)中FlatMap用來(lái)使多為數(shù)組扁平化為一位數(shù)組,并且在swift4.1中被重命名為Swift 4.1中被重命名為compactMap,在Combine中flatmap的作用稍微有點(diǎn)不同。
flatmap作用是在publisher內(nèi)部仍然包含publisher時(shí)可以將事件扁平化,具體查看以下代碼:

example(of: "flatMap") {
    // 1 定義三個(gè)人用于聊天
    let 小明 = Chatter(name: "小明", message: "小明: 鄙人王小明!")
    let 老王 = Chatter(name: "老王", message: "老王: 我就是隔壁老王!")
    let 于大爺 = Chatter(name: "于大爺", message: "燙頭去")

    // 2 j可以獲取當(dāng)前值的Publishers初始值是小明
    let chat = CurrentValueSubject<Chatter, Never>(小明)

//    chat
//        .flatMap(maxPublishers: .max(2)) { $0.message }
//        .sink(receiveValue: { print($0) })
//        .store(in: &subscriptions)

    chat.sink{ print($0.message.value)}

    小明.message.value = "小明: 馬冬梅在家嗎?"
    chat.value = 老王
    老王.message.value = "老王: 什么冬梅?"
    小明.message.value = "小明: 馬冬梅??!"
    chat.value = 于大爺
    老王.message.value = "老王: 馬東什么?"
}

/* 輸出
——— Example of: flatMap ———
小明: 鄙人王小明!
老王: 我就是隔壁老王!
燙頭去

// 注釋chat.sink{ print($0.message.value)}打開(kāi)上放訂閱的注釋輸出
——— Example of: flatMap ———
小明: 鄙人王小明!
小明: 馬冬梅在家嗎?
老王: 我就是隔壁老王!
老王: 什么冬梅?
小明: 馬冬梅?。?老王: 馬東什么?
*/

在一開(kāi)始我們使用chat.sink{ print($0.message.value)}訂閱事輸出只有三句話,這是因?yàn)槲覀冎粚?duì)chat進(jìn)行了訂閱。當(dāng)具體的Chatter的message變化時(shí),我們并不能訂閱到事件。那我想訂閱全部的談話事件怎么辦呢?flatMap正是為此而生的,當(dāng)我們改成flatmap的訂閱后可以輸出所有publisher的事件,包括publisher的值內(nèi)部的publisher發(fā)出的事件。上面我們也提到,map操作會(huì)緩存publisher,為了防止我們緩存太多的publisher我們可以在flatmap事指定緩存的publisher個(gè)數(shù)(maxPublishers: .max(2)),所以于老師并沒(méi)有被沒(méi)緩存,也就沒(méi)有發(fā)出于老師說(shuō)話的事件。如果未指定個(gè)數(shù),則maxPublishers默認(rèn)為.unlimited

15785615311395.jpg

compactMap

和swift標(biāo)準(zhǔn)庫(kù)中的數(shù)組操作符一樣,如果你在轉(zhuǎn)換時(shí)不需要轉(zhuǎn)換失敗的nil值,你使用此方法將的到一個(gè)沒(méi)有可選值的序列

example(of: "compactMap") {
    let strings = ["a", "1.24", "3", "def", "45", "0.23"].publisher

    // 2
    strings
        .compactMap { Float($0) }
        .sink(receiveValue: { print($0)})
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: compactMap ———
1.24
3.0
45.0
0.23
*/

replaceNil(with:)

對(duì)的它的作用和方法名一樣直白,就是在遇到可選值為空時(shí)用默認(rèn)值替換空值,原始的序列也變成一個(gè)非空序列

example(of: "replaceNil") {
  ["A", nil, "C"].publisher
    .replaceNil(with: "-")
    .map { $0! }
    .sink(receiveValue: { print($0) }) 
    .store(in: &subscriptions)
}
/* 輸出
——— Example of: replaceNil ———
A
-
C
*/

replaceEmpty(with:)

替換空序列

example(of: "replaceEmpty(with:)") {
  let empty = Empty<Int, Never>()
  empty
    .replaceEmpty(with: 1)
    .sink(receiveCompletion: { print($0) },
          receiveValue: { print($0) })
    .store(in: &subscriptions)
}

Empty:創(chuàng)建一個(gè)只發(fā)出完成事件的序列

scan(::)

掃描之前的序列中所有元素,運(yùn)用函數(shù)計(jì)算新值,接收一個(gè)初始值和每次接受到新元素的函數(shù)

example(of: "scan") {
    // 1 一共進(jìn)了10個(gè)球 每個(gè)球進(jìn)球得分隨機(jī)1~3分,每次進(jìn)球后打印當(dāng)前總分
    let score = (1..<10).compactMap { _ in (1...3).randomElement() }
    score
        .publisher
        .print()
        .scan(0, +)
        .sink(receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: scan ———
receive subscription: ([1, 1, 2, 1, 1, 2, 3, 1, 3])
request unlimited
receive value: (1)
1
receive value: (1)
2
receive value: (2)
4
receive value: (1)
5
receive value: (1)
6
receive value: (2)
8
receive value: (3)
11
receive value: (1)
12
receive value: (3)
15
receive finished
*/

注意.scan(0, +)這里的 + 是一個(gè)函數(shù),你可以在Xcode點(diǎn)擊查看其聲明
public static func + (lhs: Int, rhs: Int) -> Int

tryScan

作為一名有經(jīng)驗(yàn)的程序員,你應(yīng)該能自己聯(lián)想到他的功能,對(duì)就是你想的那樣。

在后面的操作符中如果沒(méi)有特殊功能將不再單獨(dú)介紹相關(guān)的try運(yùn)算符,但我會(huì)告訴你它的存在

Filtering

和標(biāo)準(zhǔn)庫(kù)的Array的方法一樣,該方法也是接受一個(gè)返回Bool值的函數(shù)過(guò)濾元素,返回false的值將被過(guò)濾掉

example(of: "filter") {
    let numbers = [(1,2),(2,4),(3,1),(6,2),(1,0)].publisher

    // 過(guò)濾掉第一個(gè)值小于第二個(gè)值的元祖
    numbers
        .filter( > )
        .sink(receiveValue: { print("\($0) 大于 \($1)") })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: filter ———
3 大于 1
6 大于 2
1 大于 0
*/

注意此處的 >是一個(gè)函數(shù),這里的參數(shù)可以是函數(shù)(或者閉包-匿名函數(shù))
public static func > (lhs: Int, rhs: Int) -> Bool

removeDuplicates

過(guò)濾掉連續(xù)的重復(fù)值


15828721202656.jpg
example(of: "removeDuplicates") {
    // 1
    let userInput = ["aaa", "aaa", "bbbb", "ccc", "bbbb"].publisher

    // 2
    userInput
        .removeDuplicates()
        .sink(receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: removeDuplicates ———
aaa
bbbb
ccc
bbbb
*/

ignoreOutput

忽略發(fā)送的值,如果有的時(shí)候你只在乎publisher有沒(méi)有完成發(fā)送二不關(guān)心他具體發(fā)送了那些值,可已使用ignoreOutput,使用后將只會(huì)訂閱到完成事件(錯(cuò)誤完成或者正常結(jié)束)

example(of: "ignoreOutput") {
    // 1
    let numbers = (1...10_000).publisher
    // 2
    numbers
        .ignoreOutput()
        .sink(receiveCompletion: { print("Completed with: \($0)") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)
}

/* 輸出
——— Example of: ignoreOutput ———
Completed with: finished
*/

compactMap

轉(zhuǎn)換時(shí)忽略掉無(wú)法轉(zhuǎn)換的值,和標(biāo)準(zhǔn)庫(kù)中的Array 的同名方法類(lèi)似

example(of: "compactMap") {
    let strings = ["http://www.baidu.com", "dkjone://happy.lv", "哈利路亞", "", "https://127.0.0.1"].publisher

    strings
        .compactMap(URL.init(string:))
        .sink(receiveValue: { print($0.absoluteString) })
        .store(in: &subscriptions)
}

/* 輸出
——— Example of: compactMap ———
http://www.baidu.com
dkjone://happy.lv
https://127.0.0.1
*/

first(where:)

找到序列中的第一個(gè)滿(mǎn)足條件的值然后發(fā)出,并且發(fā)送完成事件,取消上游的publishers繼續(xù)向其發(fā)送值

example(of: "first(where:)") {
    let numbers = (1...9).publisher
    numbers
        .print("numbers")
        .first(where: { $0 % 2 == 0 })
        .sink(receiveCompletion: { print("Completed with: \($0)") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: first(where:) ———
numbers: receive subscription: (1...9)
numbers: request unlimited
numbers: receive value: (1)
numbers: receive value: (2)
numbers: receive cancel
2
Completed with: finished
*/

last(where:)

與first(where:)相反,此運(yùn)算符是貪婪的,因?yàn)樗仨毜却兄蛋l(fā)出,才能知道是否找到匹配的值。因此,上游必須是一個(gè)已經(jīng)經(jīng)完成的publisher

example(of: "last(where:)") {
    let numbers = PassthroughSubject<Int, Never>()
    numbers
        .last(where: { $0 % 2 == 0 })
        .sink(receiveCompletion: { print("Completed with: \($0)") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)

    numbers.send(1)
    numbers.send(2)
    numbers.send(3)
    numbers.send(4)
    numbers.send(5)
    numbers.send(completion: .finished)
}
/* 輸出
——— Example of: last(where:) ———
4
Completed with: finished
*/

dropFirst

忽略指定個(gè)數(shù)的值

example(of: "dropFirst") {
    let numbers = (1...10).publisher
    numbers
        .dropFirst(8)
        .sink(receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: dropFirst ———
9
10
*/

drop(while:)

忽略序列中的值直到滿(mǎn)足條件時(shí)。

 example(of: "drop(while:)") {
    let numbers = (1...10).publisher
    numbers
        .drop(while: { $0 % 5 != 0 })
        .sink(receiveValue: { print($0) })
        .store(in: &subscriptions)
}

/* 輸出
——— Example of: drop(while:) ———
5
6
7
*/

drop(untilOutputFrom:)

忽略序列中對(duì)的值直到另一個(gè)序列開(kāi)始發(fā)送值

 example(of: "drop(untilOutputFrom:)") {
    let isReady = PassthroughSubject<Void, Never>()
    let taps = PassthroughSubject<Int, Never>()

    taps
        .drop(untilOutputFrom: isReady)
        .sink(receiveValue: {
            print($0)
        })
        .store(in: &subscriptions)

    (1...5).forEach { n in
        taps.send(n)
        if n == 3 {
            isReady.send()
        }
    }
}
/* 輸出
——— Example of: drop(untilOutputFrom:) ———
4
5
*/

prefix

獲取序列中指定個(gè)數(shù)的值,然后發(fā)出完成事件

 example(of: "prefix") {
    let numbers = (1...10).publisher
    numbers
        .prefix(2)
        .sink(receiveCompletion: { print("Completed with: \($0)") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: prefix ———
1
2
Completed with: finished
*/

prefix(while:)

獲取序列中的值直到滿(mǎn)足給定的條件,然后發(fā)出完成事件,與 drop(while:)相反


15828722470169.jpg

prefix(untilOutputFrom:)

獲取序列中的值直到給定的序列發(fā)出值,然后發(fā)出完成事件,與 drop(untilOutputFrom:)相反


15828722334301.jpg

prepend

在原始的publisher序列前面追加給定的值,值的類(lèi)型必須與原始序列類(lèi)型一致


15828726074065.jpg
 example(of: "prepend(Output...)") {
  let publisher = [3, 4].publisher
  publisher
    .prepend(1, 2)
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)
}
/* 輸出
——— Example of: prepend(Output...) ———
1
2
3
4
*/

prepend(Sequence)

在原始的publisher序列前面追加給定序列中的所有值,值的類(lèi)型必須與原始序列類(lèi)型一致

prepend(Publisher)

在原始的publisher序列前面追加給定publisher 序列中的所有值,值的類(lèi)型必須與原始序列類(lèi)型一致,如果追加的publisher是一個(gè)未完成的序列,會(huì)等新追加序列發(fā)送完成事件再發(fā)送原始序列中的值

example(of: "prepend(Publisher) #2") {
  let publisher1 = [3, 4].publisher
  let publisher2 = PassthroughSubject<Int, Never>()

  publisher1
    .prepend(publisher2)
    .sink(receiveValue: { print($0) })
    .store(in: &subscriptions)

  publisher2.send(1)
  publisher2.send(2)
//  publisher2.send(completion: .finished)
}
/* 輸出
——— Example of: prepend(Publisher) ———
1
2

//打開(kāi)最后一行注釋后輸出
——— Example of: prepend(Publisher) ———
1
2
3
4
*/

append()

與prepend() 類(lèi)似,只是位置改為在原始序列末尾追加

append(Sequence)

與prepend(Sequence) 類(lèi)似,只是位置改為在原始序列末尾追加

15828732022683.jpg
 example(of: "append(Output...)") {
    let publisher = [1].publisher

    publisher
        .append(2, 3)
        .append(4)
        .sink(receiveValue: { print($0) })
        .store(in: &subscriptions)
}
/* 輸出
——— Example of: append(Output...) ———
1
2
3
4
*/

append(Publisher)

與prepend(Publisher) 類(lèi)似,只是位置改為在原始序列末尾追加

switchToLatest

從一個(gè)publiser切換到另一個(gè),這會(huì)停止接收之前publisher的值而改成接收新切換的publisher序列中的值


15828737758818.jpg
 example(of: "switchToLatest") {
    let publisher1 = PassthroughSubject<Int, Never>()
    let publisher2 = PassthroughSubject<Int, Never>()
    let publisher3 = PassthroughSubject<Int, Never>()

    let publishers = PassthroughSubject<PassthroughSubject<Int, Never>, Never>()

    publishers
        .switchToLatest()
        .sink(receiveCompletion: { _ in print("Completed!") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)

    publishers.send(publisher1)
    publisher1.send(1)
    publisher1.send(2)

    publishers.send(publisher2)
    publisher1.send(3)
    publisher2.send(4)
    publisher2.send(5)

    publishers.send(publisher3)
    publisher2.send(6)
    publisher3.send(7)
    publisher3.send(8)
    publisher3.send(9)

    publisher3.send(completion: .finished)
    publishers.send(completion: .finished)
}
/* 輸出
——— Example of: switchToLatest ———
1
2
4
5
7
8
9
Completed!
*/

merge(with:)

與RXSwift中的同名操作符效果一致,將publishers中的值按時(shí)間順序合并成一個(gè)publisher,值類(lèi)型必須一致

image
example(of: "merge(with:)") {
    let publisher1 = PassthroughSubject<Int, Never>()
    let publisher2 = PassthroughSubject<Int, Never>()

    publisher1
        .merge(with: publisher2)
        .sink(receiveCompletion: { _ in print("Completed") },
              receiveValue: { print($0) })
        .store(in: &subscriptions)

    publisher1.send(1)
    publisher1.send(2)

    publisher2.send(3)

    publisher1.send(4)

    publisher2.send(5)

    publisher1.send(completion: .finished)
    publisher2.send(completion: .finished)
}

/* 輸出
——— Example of: merge(with:) ———
1
2
3
4
5
Completed
*/

combineLatest

與RXSwift中的同名操作符效果一致,當(dāng)多個(gè) publisher 中任何一個(gè)發(fā)出一個(gè)元素,就發(fā)出一個(gè)元素。這個(gè)元素是由這些 publisher 中最新的元素組合起來(lái)的元組,各個(gè)publisher的值類(lèi)型可以不一樣


15828766695342.jpg
example(of: "combineLatest") {
    let publisher1 = PassthroughSubject<Int, Never>()
    let publisher2 = PassthroughSubject<String, Never>()

    publisher1
        .combineLatest(publisher2)
        .sink(receiveCompletion: { _ in print("Completed") },
              receiveValue: { print("P1: \($0), P2: \($1)") })
        .store(in: &subscriptions)

    publisher1.send(1)
    publisher1.send(2)

    publisher2.send("a")
    publisher2.send("b")

    publisher1.send(3)

    publisher2.send("c")

    publisher1.send(completion: .finished)
    publisher2.send(completion: .finished)
}

/* 輸出
——— Example of: combineLatest ———
P1: 2, P2: a
P1: 2, P2: b
P1: 3, P2: b
P1: 3, P2: c
Completed
*/

zip

與swift標(biāo)準(zhǔn)庫(kù)和RXSwift的同名函數(shù)左營(yíng)類(lèi)似,在publisher相同索引處發(fā)出成對(duì)值的元組。它等待每個(gè)publisher發(fā)出一個(gè)值,然后在所有publisher在當(dāng)前索引處發(fā)出一個(gè)元素后發(fā)出一個(gè)值的元組。這意味著,如果zip兩個(gè)publisher,則每次兩個(gè)發(fā)布服務(wù)器都發(fā)出一個(gè)值時(shí),才會(huì)發(fā)出一個(gè)元組。


image
example(of: "zip") {
    let publisher1 = PassthroughSubject<Int, Never>()
    let publisher2 = PassthroughSubject<String, Never>()

    publisher1
        .zip(publisher2)
        .sink(receiveCompletion: { _ in print("Completed") },
              receiveValue: { print("P1: \($0), P2: \($1)") })
        .store(in: &subscriptions)

    publisher1.send(1)
    publisher1.send(2)

    publisher2.send("a")
    publisher2.send("b")

    publisher1.send(3)

    publisher2.send("c")
    publisher2.send("d")

    publisher1.send(completion: .finished)
    publisher2.send(completion: .finished)
}

/* 輸出
——— Example of: zip ———
P1: 1, P2: a
P1: 2, P2: b
P1: 3, P2: c
Completed
*/

delay(for)

延遲發(fā)出元素,接受一個(gè)延遲時(shí)間參數(shù),以及要運(yùn)行的線程

var subscriptions = Set<AnyCancellable>()
let start = Date()
let deltaFormatter: NumberFormatter = {
    let f = NumberFormatter()
    f.negativePrefix = ""
    f.minimumFractionDigits = 1
    f.maximumFractionDigits = 1
    return f
}()

/// 本頁(yè)代碼運(yùn)行時(shí)初始化時(shí)間, 計(jì)算運(yùn)行到固定行數(shù)時(shí)得到時(shí)間差
public var deltaTime: String {
    return deltaFormatter.string(for: Date().timeIntervalSince(start))!
}

example(of: "Delay") {
    let publisher = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    publisher.sink { date in
        print("origin:\t" + "\(deltaTime)\t" + date.description)
    }.store(in: &subscriptions)

    publisher.delay(for: .seconds(2), scheduler: DispatchQueue.main).sink { date in
        print("delay:\t" + "\(deltaTime)\t" + date.description)
    }.store(in: &subscriptions)
}

/* 輸出
——— Example of: Delay ———
origin: 1.1 2020-03-02 06:33:55 +0000
origin: 2.1 2020-03-02 06:33:56 +0000
origin: 3.1 2020-03-02 06:33:57 +0000
delay:  3.3 2020-03-02 06:33:55 +0000
origin: 4.1 2020-03-02 06:33:58 +0000
delay:  4.1 2020-03-02 06:33:56 +0000
...
*/

autoconnect() 在第一次訂閱時(shí)立即連接。

Collect

將原始序列中的元素組成集合發(fā)出,可以接受的參數(shù)有集合個(gè)數(shù)、時(shí)間、個(gè)數(shù)或時(shí)間。滿(mǎn)足參數(shù)條件就會(huì)發(fā)出集合,否則等待元素。(參數(shù)是時(shí)間和個(gè)數(shù)都設(shè)置時(shí)滿(mǎn)足任一就會(huì)發(fā)出)

example(of: "Collect") {
    let publisher = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    publisher.sink { date in
        print("origin:\t" + "\(deltaTime)\t" + date.description)
    }.store(in: &subscriptions)

    publisher.collect(.byTimeOrCount(DispatchQueue.main, .seconds(5), 3), options: .none) .sink { date in
        print("collect:\t" + "\(deltaTime)\t" + date.description)
    }.store(in: &subscriptions)
}
/* 輸出
——— Example of: Collect ———
origin: 1.1 2020-03-02 07:38:26 +0000
origin: 2.1 2020-03-02 07:38:27 +0000
origin: 3.1 2020-03-02 07:38:28 +0000
collect:    3.1 [2020-03-02 07:38:26 +0000, 2020-03-02 07:38:27 +0000, 2020-03-02 07:38:28 +0000]
origin: 4.1 2020-03-02 07:38:29 +0000
origin: 5.1 2020-03-02 07:38:30 +0000
collect:    5.1 [2020-03-02 07:38:29 +0000, 2020-03-02 07:38:30 +0000]
...
*/

Debounce(for)

與RXSwift同名操作符作用一致,等待多長(zhǎng)時(shí)間后沒(méi)有新值再發(fā)出該值,忽略中間連續(xù)變化的值


debonce
example(of: "Debounce") {
   let publisher = PassthroughSubject<String,Never>()
   let typingHelloWorld: [(TimeInterval, String)] = [
      (0.0, "H"),
      (0.1, "He"),
      (0.2, "Hel"),
      (0.3, "Hell"),
      (0.5, "Hello"),
      (0.6, "Hello "),
      (2.0, "Hello W"),
      (2.1, "Hello Wo"),
      (2.2, "Hello Wor"),
      (2.4, "Hello Worl"),
      (2.5, "Hello World")
    ]
    //模擬輸入Hello Word
    typingHelloWorld.forEach { (delay,str) in
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            publisher.send(str)
        }
    }

    publisher.sink { data in
        print("origin:\t" + "\(deltaTime)\t" + data)
    }.store(in: &subscriptions)

    publisher.debounce(for: .seconds(1), scheduler: DispatchQueue.main).sink { data in
        print("debounce:\t" + "\(deltaTime)\t" + data)
    }.store(in: &subscriptions)
}

/* 輸出
——— Example of: Debounce ———
origin: 0.1 H
origin: 0.2 He
origin: 0.3 Hel
origin: 0.4 Hell
origin: 0.6 Hello
origin: 0.7 Hello 
debounce:   1.7 Hello 
origin: 2.2 Hello W
origin: 2.2 Hello Wo
origin: 2.5 Hello Wor
origin: 2.5 Hello Worl
origin: 2.8 Hello World
debounce:   3.8 Hello World
*/

throttle

與RXSwift同名操作符效果一致,在固定時(shí)間內(nèi)只發(fā)出一個(gè)值,過(guò)濾掉其他值,你可以選擇最新的值或者第一個(gè)值發(fā)出

example(of: "throttle") {
   let publisher = PassthroughSubject<String,Never>()

    //模擬輸入Hello Word
    typingHelloWorld.forEach { (delay,str) in
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            publisher.send(str)
        }
    }

    publisher.sink { data in
        print("origin:\t" + "\(deltaTime)\t" + data)
    }.store(in: &subscriptions)

    publisher.throttle(for: .seconds(1), scheduler: DispatchQueue.main, latest: false).sink { data in
        print("throttle:\t" + "\(deltaTime)\t" + data)
    }.store(in: &subscriptions)
}
/* 輸出
——— Example of: throttle ———
origin: 0.1 H
throttle:   0.1 H
origin: 0.2 He
origin: 0.3 Hel
origin: 0.4 Hell
origin: 0.6 Hello
origin: 0.7 Hello 
throttle:   1.2 Hello 
origin: 2.2 Hello W
origin: 2.2 Hello Wo
throttle:   2.2 Hello Wo
origin: 2.5 Hello Wor
origin: 2.5 Hello Worl
origin: 2.8 Hello World
throttle:   3.5 Hello World
*/

Timeout

與RXSwift同名操作符一樣,超出給定的時(shí)間后發(fā)出結(jié)束事件,你可以給出自定義錯(cuò)誤類(lèi)型,這樣在超時(shí)后會(huì)發(fā)出錯(cuò)誤完成事件


image

Measuring time

用于調(diào)試的操作符,計(jì)算兩次值發(fā)出的時(shí)間間隔,單位是納秒

min

發(fā)出原始序列中的最小值,然后發(fā)出完成事件。要求序列是已完成的序列否則會(huì)等待原始序列的完成事件。

max

與min相反,發(fā)出原始序列中的最大值,然后發(fā)出完成事件。要求序列是已完成的序列否則會(huì)等待原始序列的完成事件。

first

發(fā)出原始序列中的第一個(gè)值,然后發(fā)出完成事件

last

與first相反,發(fā)出原始序列中的最后一個(gè)值,然后發(fā)出完成事件。要求序列是已完成的序列否則會(huì)等待原始序列的完成事件。

output(in:)

output(at:)發(fā)出指定位置的值,output(in:)發(fā)出指定范圍內(nèi)的值

example(of: "output(in:)") {
  let publisher = ["A", "B", "C", "D", "E"].publisher
  publisher
    .print("publisher")
    .output(in: 1...3)
    .sink(receiveCompletion: { print($0) },
          receiveValue: { print("Value in range: \($0)") })
    .store(in: &subscriptions)
}
/*輸出
——— Example of: output(in:) ———
publisher: receive subscription: (["A", "B", "C", "D", "E"])
publisher: request unlimited
publisher: receive value: (A)
publisher: request max: (1) (synchronous)
publisher: receive value: (B)
Value in range: B
publisher: receive value: (C)
Value in range: C
publisher: receive value: (D)
Value in range: D
publisher: receive cancel
finished
*/

count

記錄原始序列發(fā)出值的個(gè)數(shù),并發(fā)出

contains

原始publisher發(fā)出指定值,則contains運(yùn)算符將發(fā)出true并取消訂閱;如果原始publisher已完成且發(fā)出的值均不等于指定值,則發(fā)出false

reduce

與標(biāo)準(zhǔn)庫(kù)函數(shù)類(lèi)似,在原始publisher完成時(shí)發(fā)出累計(jì)計(jì)算的到的值


15832015826163.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容