Skip to content

Instantly share code, notes, and snippets.

@mlavergn
Created November 21, 2019 02:21
Show Gist options
  • Save mlavergn/7a42daa20bf6f65ac39fe1c5ba1616ee to your computer and use it in GitHub Desktop.
Save mlavergn/7a42daa20bf6f65ac39fe1c5ba1616ee to your computer and use it in GitHub Desktop.
Swift Combine demo with RxSwift commenting
import Foundation
import Combine
// register the observable name
extension Notification.Name {
static let DemoObservable = Notification.Name("DemoObservable")
}
// define the observable value type
struct DemoValue {
let value: String
}
// create the observable
let observable = NotificationCenter.Publisher(center: .default, name: .DemoObservable, object: nil).map {
(notification) -> String in
return (notification.object as? DemoValue)?.value ?? ""
}
// define a handler for the subscription
class DemoHandler {
var value: String = "foo"
}
// instantiate the handler
let handler = DemoHandler()
print("Pre-event: \(handler.value)")
// create a subscriber
let subscriber = Subscribers.Assign(object: handler, keyPath: \.value)
// subsubscribe to the observable
observable.subscribe(subscriber)
// publish an event
NotificationCenter.default.post(name: .DemoObservable, object: DemoValue(value: "bar"))
// value is changed post-event
print("Post-event: \(handler.value)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment