Last active
April 27, 2018 12:25
-
-
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
This file contains 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 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 | |
} | |
} |
Author
loromits
commented
Apr 27, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment