Last active
January 13, 2020 20:38
-
-
Save cenkbilgen/8318a0675af4cfa01fd89e15976eb587 to your computer and use it in GitHub Desktop.
Swift Playground for Publishers using Merge, CombineLatest & Zip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
var count = 0 | |
enum Marker: CustomDebugStringConvertible { | |
case A(Int) | |
case B(Int) | |
var debugDescription: String { | |
switch self { | |
case .A(let time): | |
return "A\(time)\(time == count ? "*" : "")" | |
case .B(let time): | |
return "B\(time)\(time == count ? "*" : "")" | |
} | |
} | |
} | |
Timer.publish(every: 1, on: .main, in: .default) | |
.autoconnect() | |
.sink { _ in count += 1 } | |
let publisherA = Timer.publish(every: 2, on: .main, in: .default) | |
.autoconnect() | |
.map { _ in Marker.A(count) } | |
let publisherB = Timer.publish(every: 3, on: .main, in: .default) | |
.autoconnect() | |
.map { _ in Marker.B(count) } | |
Publishers.Merge(publisherA, publisherB) | |
.sink { print("Time \(count): Merge \($0)") } | |
Publishers.CombineLatest(publisherA, publisherB) | |
.sink { print("Time \(count): CombineLatest \($0), \($1)") } | |
Publishers.Zip(publisherA, publisherB) | |
.sink { print("Time \(count): Zip \($0), \($1)") } | |
RunLoop.main.run() | |
/* Using Merge | |
Time 2: Merge A2* | |
Time 3: Merge B3* | |
Time 4: Merge A4* | |
Time 6: Merge A6* | |
Time 6: Merge B6* | |
Time 8: Merge A8* | |
Time 9: Merge B9* | |
Time 10: Merge A10* | |
Time 12: Merge A12* | |
Time 12: Merge B12* | |
Publishes any time any Publisher publishes. | |
*/ | |
/* Using CombineLatest | |
Time 3: CombineLatest A2, B3* | |
Time 4: CombineLatest A4*, B3 | |
Time 6: CombineLatest A6*, B3 | |
Time 6: CombineLatest A6*, B6* | |
Time 8: CombineLatest A8*, B6 | |
Time 9: CombineLatest A8, B9* | |
Time 10: CombineLatest A10*, B9 | |
Time 12: CombineLatest A12*, B9 | |
Time 12: CombineLatest A12*, B12* | |
Time 14: CombineLatest A14*, B12 | |
Publishes tuple of most recent Output any time any Publisher publishes, starting after all Publishers have published something. | |
*/ | |
/* Using Zip | |
Time 3: Zip A2, B3* | |
Time 6: Zip A4, B6* | |
Time 9: Zip A6, B9* | |
Time 12: Zip A8, B12* | |
Time 15: Zip A10, B15* | |
Time 18: Zip A12, B18* | |
Time 21: Zip A14, B21* | |
Time 24: Zip A16, B24* | |
Publishes tuple of most recent Output when all Publishers have published something new. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment