Skip to content

Instantly share code, notes, and snippets.

@mlavergn
Last active November 21, 2019 04:33
Show Gist options
  • Save mlavergn/6bf71c2f982b2731995970daa6ad2c3b to your computer and use it in GitHub Desktop.
Save mlavergn/6bf71c2f982b2731995970daa6ad2c3b to your computer and use it in GitHub Desktop.
Swift Combine wrapped to be RxSwift-like
import Foundation
import Combine
// define the observable value type
struct DemoValue {
var value: String
}
// observable class
class DemoObservable {
// class to pipe data dadSet event to a completion block
private class EventPipe {
var dataBlock: ((_ :DemoValue) -> Void)
var data: DemoValue? {
didSet(data) {
// on didSet, call the dataBlock with the value
self.dataBlock(self.data ?? DemoValue(value: ""))
}
}
init(_ dataBlock: @escaping (_ :DemoValue) -> Void) {
self.dataBlock = dataBlock
}
}
// name of the observable notification
// NOTE: use a UUID if this class will be instantitated more than once
let name = Notification.Name("DemoObservable")
// reference to the subject so we can post nexts
let subject: Publishers.Map<NotificationCenter.Publisher, DemoValue?>
// initializer
init() {
subject = NotificationCenter.Publisher(center: .default, name: name, object: nil).map{
(notification) -> DemoValue? in
return (notification.object as? DemoValue)
}
}
// post a next event
func next(_ demo: DemoValue) {
NotificationCenter.default.post(name: name, object: demo)
}
// subscribe via completion block
func subscribe(_ dataBlock: @escaping (_ :DemoValue) -> Void) {
let evPipe = EventPipe(dataBlock)
let subscriber = Subscribers.Assign(object: evPipe, keyPath: \.data)
subject.subscribe(subscriber)
}
}
// create an observable
let observable = DemoObservable();
// subscribes
observable.subscribe({
// process data
print("A:", $0)
})
observable.subscribe({
// process data
print("B:", $0)
})
// publish an events
observable.next(DemoValue(value: "foo"))
observable.next(DemoValue(value: "bar"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment