/
Contents.swift
98 lines (84 loc) · 2.58 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Combine
import Foundation
var subscription = Set<AnyCancellable>()
func example(title: String, action: () -> Void) {
print("// \(title) 예제 코드")
action()
print("\n")
}
example(title: "Collect") {
let intPublisher = [1, 2, 3, 4, 5].publisher
intPublisher
.collect()
.sink(receiveValue: { print($0) })
}
example(title: "CollectByCount") {
let intPublisher = [1, 2, 3, 4, 5].publisher
intPublisher
.collect(2)
.sink(receiveValue: { print($0) })
}
example(title: "CollectByTime-byTime") {
// let timerPublisher = Timer.publish(every: 0.5, on: .main, in: .default)
//
// timerPublisher
// .autoconnect()
// .collect(.byTime(RunLoop.main, .seconds(5)))
// .sink(receiveValue: { print($0) })
// .store(in: &subscription)
//
// timerPublisher
// .autoconnect()
// .collect(.byTime(DispatchQueue.main, .seconds(1)))
// .sink(receiveValue: { print($0) })
// .store(in: &subscription)
}
example(title: "CollectByTime-byTimeOrCount") {
// let timerPublisher = Timer.publish(every: 0.5, on: .main, in: .default)
//
// timerPublisher
// .autoconnect()
// .collect(.byTimeOrCount(DispatchQueue.main, .seconds(4), 2))
// .sink(receiveValue: { print($0) })
// .store(in: &subscription)
}
example(title: "IgnoreOutput") {
let intPublisher = [1, 2, 3, 4, 5].publisher
intPublisher
.ignoreOutput()
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
}
example(title: "Reduce") {
let intPublisher = [1, 2, 3, 4, 5].publisher
intPublisher
.reduce(0, { $0 + $1 })
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
}
example(title: "Reduce-String") {
let stringPublisher = ["P", "I", "N", "G", "U"].publisher
stringPublisher
.reduce("", { $0 + $1 })
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
}
example(title: "TryReduce") {
enum PinguError: Error {
case nagativeNumber
}
func checkNagativeNumber(_ number: Int) throws -> Int {
guard number < 0 else {
throw PinguError.nagativeNumber
}
return number
}
let intPublisher = [1, 2, 3, -10, 4].publisher
intPublisher
.tryReduce(0) { reduceValue, newValue in
try checkNagativeNumber(reduceValue + newValue)
return reduceValue + newValue
}
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
}