Created
September 9, 2019 07:35
-
-
Save darrarski/817826736b60d24d4d6bbe22455a18f7 to your computer and use it in GitHub Desktop.
Simple extension to materialize Combine publishers (helpful when unit testing)
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 Combine | |
extension Publisher { | |
func materialize() -> Result<[Output], Failure> { | |
var values = [Output]() | |
var result: Result<[Output], Failure>! | |
let semaphore = DispatchSemaphore(value: 0) | |
let subscription = sink(receiveCompletion: { completion in | |
switch completion { | |
case .finished: | |
result = .success(values) | |
case .failure(let error): | |
result = .failure(error) | |
} | |
semaphore.signal() | |
}, receiveValue: { value in | |
values.append(value) | |
}) | |
semaphore.wait() | |
subscription.cancel() | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment