Skip to content

Instantly share code, notes, and snippets.

@wotjd
Last active May 3, 2022 06:19
Show Gist options
  • Save wotjd/79fbb3d9d7307a0b9ba0330c75778cc6 to your computer and use it in GitHub Desktop.
Save wotjd/79fbb3d9d7307a0b9ba0330c75778cc6 to your computer and use it in GitHub Desktop.
import RxSwift
import RxCocoa
@dynamicMemberLookup
protocol DynamicMemberLookupableObservableType: AssociateObservable {
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> Observable<T> { get }
}
extension DynamicMemberLookupableObservableType {
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> Observable<T> {
self.myself.map({ $0[keyPath: keyPath] })
}
}
extension Observable: DynamicMemberLookupableObservableType { }
@dynamicMemberLookup
protocol DynamicMemberLookupableBinder {
associatedtype Element
subscript<T>(dynamicMember keyPath: ReferenceWritableKeyPath<Element, T>) -> Binder<T> { get }
}
extension Reactive: DynamicMemberLookupableBinder where Base: AnyObject {
typealias Element = Base
subscript<T>(dynamicMember keyPath: ReferenceWritableKeyPath<Element, T>) -> Binder<T> {
Binder(self.base) { base, value in
base[keyPath: keyPath] = value
}
}
}
// usage
Observable.just("ABC").first // Observable<Character?>
SomeButton.rx.isHighlighted // Binder<Bool>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment