Skip to content

Instantly share code, notes, and snippets.

@HashNuke
Last active August 31, 2022 11:24
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 HashNuke/248a92f0be4441e02846cdd532192f40 to your computer and use it in GitHub Desktop.
Save HashNuke/248a92f0be4441e02846cdd532192f40 to your computer and use it in GitHub Desktop.
import Combine
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var publisher = PassthroughSubject<Int, Error>()
let cancellable = publisher
.flatMap { Just($0).setFailureType(to: Error.self) }
.handleEvents(
receiveOutput: {(n:Int) in
if n < 5 {
publisher.send(n + 1)
} else {
publisher.send(completion: .finished)
}
}
)
.reduce([Int](), {allItems, n in
print("Collecting items in reduce:", allItems.count)
return allItems + [n]
})
.sink(
receiveCompletion: {completion in
switch completion {
case .finished:
print("Completed")
break
case .failure(let error):
print(error.localizedDescription)
}
},
receiveValue: { values in
print("All values:", values)
}
)
publisher.send(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment