Skip to content

Instantly share code, notes, and snippets.

@andreasmpet
Created September 22, 2017 12:29
Show Gist options
  • Save andreasmpet/fef217d5046d78b94eaded7f34c2c2a2 to your computer and use it in GitHub Desktop.
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
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