Last active
August 10, 2017 21:13
-
-
Save ncreated/8564575babd5b2316a0ab25fda3d6456 to your computer and use it in GitHub Desktop.
Medium blogpost snippet
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
| func manage(change: Observable<Bool>) -> (value: Driver<ToggleValue>, isBusy: Driver<Bool>) { | |
| let storage = self.storage | |
| let isBusySubject = PublishSubject<Bool>() | |
| let isBusy = isBusySubject | |
| .asDriver(onErrorJustReturn: false) | |
| .startWith(true) | |
| let initialValue = storage | |
| .read() | |
| .map { ToggleValue.initial($0) } | |
| .catchError { Observable.just( ToggleValue.unknown($0) ) } | |
| .do(onNext: { _ in isBusySubject.onNext(false) }) | |
| let valueAfterSaving = change | |
| .do(onNext: { _ in isBusySubject.onNext(true) }) | |
| .flatMap { valueToSave -> Observable<ToggleValue> in | |
| storage | |
| .save(value: valueToSave) | |
| .map { ToggleValue.updated(valueToSave) } | |
| .catchErrorJustReturn(ToggleValue.fallback(!valueToSave)) | |
| } | |
| .do(onNext: { _ in isBusySubject.onNext(false) }) | |
| let value = Observable.merge(initialValue, valueAfterSaving) | |
| .asDriver(onErrorRecover: { Driver.just(ToggleValue.unknown($0)) }) | |
| return (value: value, isBusy: isBusy) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment