Skip to content

Instantly share code, notes, and snippets.

@darrarski
Created September 9, 2019 07:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrarski/817826736b60d24d4d6bbe22455a18f7 to your computer and use it in GitHub Desktop.
Save darrarski/817826736b60d24d4d6bbe22455a18f7 to your computer and use it in GitHub Desktop.
Simple extension to materialize Combine publishers (helpful when unit testing)
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