Skip to content

Instantly share code, notes, and snippets.

@erica

erica/combine2.swift

Created Jul 11, 2020
Embed
What would you like to do?
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."
// WHAT'S THERE:
// 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>()
passthroughSubject.send("foo")
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.send("Hello")
passthroughSubject.sink { completionInfo in
switch completionInfo {
case .finished: print("Done!!")
case .failure(let error): print("Error: \(error)")
}
} receiveValue: { stringElement in
print(stringElement, "received")
}
passthroughSubject.send("World")
// 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
You can’t perform that action at this time.