Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2020 03:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save erica/060b446d94facc00dd75db2bade5dd16 to your computer and use it in GitHub Desktop.
import Cocoa
import Combine
// ## Subjects
// A `Subject` is a special publisher that enables you to inject values into a stream.
// Just call the `send(_:)` method.
// "This can be useful for adapting existing imperative code to the Combine model."
// A publisher that exposes a method for outside callers to publish elements.
// Subject
// A subject that broadcasts elements to downstream subscribers.
// PassthroughSubject
// A subject that wraps a single value and publishes a new element whenever the value changes.
// CurrentValueSubject
// Let's send Strings! PassthroughSubject only sends values for AFTER subscription
let passthroughSubject = PassthroughSubject<String,Error>()
struct SomethingBad: Error, CustomStringConvertible {
var description: String = "Bad"
// If you uncomment this, you will either finish or get the error to handle as the finish
// state is _already_ in place.
switch Bool.random() {
case true: // Success
passthroughSubject.send(completion: .finished)
case false: // Error
passthroughSubject.send(completion: .failure(SomethingBad()))
passthroughSubject.sink { completionInfo in
switch completionInfo {
case .finished: print("Done!!")
case .failure(let error): print("Error: \(error)")
} receiveValue: { stringElement in
print(stringElement, "received")
// So this is a kind of crappy example, so next build a better passthrough example using an async data source.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment