Last active
November 16, 2020 10:41
-
-
Save susieyy/3e1059d5dc9d0f2278db07e3fb73332f to your computer and use it in GitHub Desktop.
Examines an issue where the MergeMany operator in Combine may not perform background processing.
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 | |
// see: workaround https://gist.github.com/susieyy/95e8f55fd077162c7e02c13b541e8309 | |
// Examines an issue where the MergeMany operator in Combine may not perform background processing. | |
// $ swift --version | |
// Apple Swift version 5.3.1 (swiftlang-1200.0.41 clang-1200.0.32.8) | |
// Target: x86_64-apple-darwin20.1.0 | |
// $ xcodebuild -version | |
// Xcode 12.2 | |
// Build version 12B5044c | |
let workers: [AnyPublisher<String, Never>] = (0..<20).map { | |
Just<Int>($0) | |
.receive(on: DispatchQueue.global()) | |
.map { | |
print("Working: isMainThread [\(Thread.isMainThread)] [\($0)]") | |
return String($0) | |
} | |
.eraseToAnyPublisher() | |
} | |
var cancellables: Set<AnyCancellable> = .init() | |
print("Workers initial count: \(workers.count)") | |
Publishers | |
.MergeMany(workers) | |
.collect() | |
.receive(on: DispatchQueue.main) | |
.sink(receiveValue: { | |
print("Workers result count: \($0.count)") | |
dump($0) | |
}) | |
.store(in: &cancellables) | |
// - OUTPUT -------------------------------------------------------- | |
// Workers initial count: 20 | |
// Working: isMainThread [false] [0] | |
// Working: isMainThread [false] [1] | |
// Working: isMainThread [false] [2] | |
// Working: isMainThread [false] [3] | |
// Working: isMainThread [false] [5] | |
// Working: isMainThread [false] [6] | |
// Working: isMainThread [false] [7] | |
// Working: isMainThread [false] [10] | |
// Working: isMainThread [false] [9] | |
// Working: isMainThread [false] [11] | |
// Working: isMainThread [false] [12] | |
// Working: isMainThread [false] [13] | |
// Working: isMainThread [false] [14] | |
// Working: isMainThread [false] [15] | |
// Working: isMainThread [false] [17] | |
// Working: isMainThread [false] [19] | |
// Working: isMainThread [false] [18] | |
// Workers result count: 17 ← Expect 20 counts | |
// ▿ 17 elements | |
// - "0" | |
// - "3" | |
// - "2" | |
// - "1" | |
// - "5" | |
// - "10" | |
// - "7" | |
// - "6" | |
// - "9" | |
// - "11" | |
// - "12" | |
// - "14" | |
// - "15" | |
// - "13" | |
// - "18" | |
// - "17" | |
// - "19" | |
// - OUTPUT -------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment