Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. extension Publisher {
  2. func toBlockingResult(timeout: Int) -> Result<[Self.Output],BlockingError> {
  3. var result : Result<[Self.Output],BlockingError>?
  4. let semaphore = DispatchSemaphore(value: 0)
  5.  
  6. let sub = self
  7. .collect()
  8. .mapError { error in BlockingError.otherError(error) }
  9. .timeout(
  10. .seconds(timeout),
  11. scheduler: DispatchQueue.main,
  12. customError: { BlockingError.timeoutError(timeout) }
  13. ).sink(
  14. receiveCompletion: { compl in
  15. switch compl {
  16. case .finished: break
  17. case .failure( let f ): result = .failure(f)
  18. }
  19. semaphore.signal()
  20. },
  21. receiveValue: { value in
  22. result = .success(value)
  23. semaphore.signal()
  24. }
  25. )
  26.  
  27. // Wait for a result, or time out
  28. if semaphore.wait(timeout: .now() + .seconds(timeout)) == .timedOut {
  29. sub.cancel()
  30. return .failure(BlockingError.timeoutError(timeout))
  31. } else {
  32. return result ?? .success([])
  33. }
  34. }
  35. }
  36.  
  37. enum BlockingError : Error {
  38. case timeoutError(Int)
  39. case otherError(Error)
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement