Last active
November 22, 2016 10:00
-
-
Save ukitaka/d71b7b29a15f20f7f422b4fabb2a9302 to your computer and use it in GitHub Desktop.
VerifiableVariable
This file contains hidden or 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
let userName = VerifiableVariable<String>("") { $0.characters.count > 0 } | |
userName.isValid | |
.bindTo(submitButton.rx.isEnabled) | |
.addDisposableTo(disposeBag) |
This file contains hidden or 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 VerifiableVariable<Element> { | |
public typealias E = Element | |
private let _subject: BehaviorSubject<Element> | |
private let _lock = NSRecursiveLock() | |
private var _value: E | |
private let _validation: (Element) -> Bool | |
public var value: E { | |
get { | |
_lock.lock(); defer { _lock.unlock() } | |
return _value | |
} | |
set(newValue) { | |
_lock.lock() | |
_value = newValue | |
_lock.unlock() | |
_subject.on(.next(newValue)) | |
} | |
} | |
public var isValid: Observable<Bool> { | |
return _subject.asObservable() | |
.map { [unowned self] in self._validation($0) } | |
} | |
public init(_ value: Element, validation: @escaping (Element) -> Bool) { | |
_value = value | |
_subject = BehaviorSubject(value: value) | |
_validation = validation | |
} | |
public func asObservable() -> Observable<E> { | |
return _subject | |
} | |
deinit { | |
_subject.on(.completed) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment