Skip to content

Instantly share code, notes, and snippets.

@loromits
Last active April 27, 2018 12:25
Show Gist options
  • Save loromits/3a046e44db6dcf8540f86aa2f11cec40 to your computer and use it in GitHub Desktop.
Save loromits/3a046e44db6dcf8540f86aa2f11cec40 to your computer and use it in GitHub Desktop.
Simple stupid internally type-erasing reactive NotificationCenter addition to handle observables through misconnected parts of application
import RxSwift
protocol Dispatchable {}
protocol DispatchableElement {}
extension PublishSubject: Dispatchable where E: DispatchableElement {}
final class EventDispatcher {
static let shared = EventDispatcher()
private let disposeBag = DisposeBag()
private var subjects = [String: Dispatchable]()
private func typeDescriptor<T>(_ type: T.Type) -> String {
return String(describing: type)
}
func update<O: ObservableType>(_ sequence: O) where O.E: DispatchableElement {
let descriptor = typeDescriptor(O.E.self)
if let subject = subjects[descriptor] as? PublishSubject<O.E> {
sequence.subscribe(subject).disposed(by: disposeBag)
} else {
let subject = PublishSubject<O.E>()
sequence.subscribe(subject).disposed(by: disposeBag)
subjects[descriptor] = subject
}
}
func onNext<E: DispatchableElement>(_ value: E) {
if let subject = subjects[typeDescriptor(E.self)] as? PublishSubject<E> {
subject.onNext(value)
}
}
func events<E: DispatchableElement>(_ type: E.Type) -> Observable<E> {
let descriptor = typeDescriptor(type)
let subject = subjects[descriptor] as? PublishSubject<E> ?? PublishSubject<E>()
subjects[descriptor] = subject
return subject
}
}
@loromits
Copy link
Author

loromits commented Apr 27, 2018

struct Dog: DispatchableElement {
    let name: String
}
_ = EventDispatcher.shared.events(Dog.self).subscribe { print($0.name) }
EventDispatcher.shared.update(Observable.from([Dog(name: "Ball"), Dog(name: "Cat")])
EventDispatcher.shared.onNext(Dog(name: "Dog"))
// "Ball"
// "Cat"
// "Dog"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment