Home rxswift control property
Post
Cancel

rxswift control property

public protocol ControlPropertyType : ObservableType, ObserverType

1
func asControlProperty() -> ControlProperty<Element>

public struct ControlProperty : ControlPropertyType

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
public typealias Element = PropertyType

let _values: Observable<PropertyType>
let _valueSink: AnyObserver<PropertyType>

public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
    return self._values.subscribe(observer)
}


    /// `ControlEvent` of user initiated value changes. Every time user updates control value change event
    /// will be emitted from `changed` event.
    ///
    /// Programmatic changes to control value won't be reported.
    ///
    /// It contains all control property values except for first one.
    ///
    /// The name only implies that sequence element will be generated once user changes a value and not that
    /// adjacent sequence values need to be different (e.g. because of interaction between programmatic and user updates,
    /// or for any other reason).
public var changed: ControlEvent<PropertyType> {
    return ControlEvent(events: self._values.skip(1))
}

public func asObservable() -> Observable<Element> {
    return self._values
}

public func asControlProperty() -> ControlProperty<Element> {
    return self
}

public func on(_ event: Event<Element>) {
    switch event {
    case .error(let error):
        bindingError(error)
    case .next:
        self._valueSink.on(event)
    case .completed:
        self._valueSink.on(event)
    }
}
1
2
3
4
5
6
7
8
9
10
extension ControlPropertyType where Element == String? {
    /// Transforms control property of type `String?` into control property of type `String`.
    public var orEmpty: ControlProperty<String> {
        let original: ControlProperty<String?> = self.asControlProperty()

        let values: Observable<String> = original._values.map { $0 ?? "" }
        let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 }
        return ControlProperty<String>(values: values, valueSink: valueSink)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension ControlProperty {
    /// Converts `ControlProperty` to `Driver` trait.
    ///
    /// `ControlProperty` already can't fail, so no special case needs to be handled.
    public func asDriver() -> Driver<Element> {
        return self.asDriver { _ -> Driver<Element> in
            #if DEBUG
                rxFatalError("Somehow driver received error from a source that shouldn't fail.")
            #else
                return Driver.empty()
            #endif
        }
    }
}
This post is licensed under CC BY 4.0 by the author.