Created
September 22, 2017 12:29
-
-
Save andreasmpet/fef217d5046d78b94eaded7f34c2c2a2 to your computer and use it in GitHub Desktop.
Wrapper for Variable in RxSwift that allows easy transformation rules for the input values
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
public class TransformingVariable<Element> : ObserverType, ObservableConvertibleType { | |
public typealias E = Element | |
public typealias TransformationBlock = (_ input: E) -> E | |
private let backingVariable: Variable<E> | |
private let transformation: TransformationBlock | |
public init(initialValue: E, transformation: @escaping TransformationBlock) { | |
self.backingVariable = Variable(initialValue) | |
self.transformation = transformation | |
} | |
public var value: E { | |
set(value) { | |
self.backingVariable.value = self.transformation(value) | |
} | |
get { | |
return self.backingVariable.value | |
} | |
} | |
public func asObservable() -> Observable<E> { | |
return self.backingVariable.asObservable() | |
} | |
public func on(_ event: Event<E>) { | |
switch event { | |
case .next(let element): | |
self.value = element | |
default: | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment