Created
July 11, 2020 03:56
-
-
Save erica/060b446d94facc00dd75db2bade5dd16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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