-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathReactive.swift
80 lines (65 loc) · 2.24 KB
/
Reactive.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// Reactive.swift
// RxSwift
//
// Created by Yury Korolev on 5/2/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
/**
Use `Reactive` proxy as customization point for constrained protocol extensions.
General pattern would be:
// 1. Extend Reactive protocol with constrain on Base
// Read as: Reactive Extension where Base is a SomeType
extension Reactive where Base: SomeType {
// 2. Put any specific reactive extension for SomeType here
}
With this approach we can have more specialized methods and properties using
`Base` and not just specialized on common base type.
`Binder`s are also automatically synthesized using `@dynamicMemberLookup` for writable reference properties of the reactive base.
*/
@dynamicMemberLookup
public struct Reactive<Base> {
/// Base object to extend.
public let base: Base
/// Creates extensions with base object.
///
/// - parameter base: Base object.
public init(_ base: Base) {
self.base = base
}
/// Automatically synthesized binder for a key path between the reactive
/// base and one of its properties
public subscript<Property>(dynamicMember keyPath: ReferenceWritableKeyPath<Base, Property>) -> Binder<Property> where Base: AnyObject {
Binder(self.base) { base, value in
base[keyPath: keyPath] = value
}
}
}
/// A type that has reactive extensions.
public protocol ReactiveCompatible {
/// Extended type
associatedtype ReactiveBase
/// Reactive extensions.
static var rx: Reactive<ReactiveBase>.Type { get set }
/// Reactive extensions.
var rx: Reactive<ReactiveBase> { get set }
}
extension ReactiveCompatible {
/// Reactive extensions.
public static var rx: Reactive<Self>.Type {
get { Reactive<Self>.self }
// this enables using Reactive to "mutate" base type
// swiftlint:disable:next unused_setter_value
set { }
}
/// Reactive extensions.
public var rx: Reactive<Self> {
get { Reactive(self) }
// this enables using Reactive to "mutate" base object
// swiftlint:disable:next unused_setter_value
set { }
}
}
import Foundation
/// Extend NSObject with `rx` proxy.
extension NSObject: ReactiveCompatible { }