Created
August 10, 2017 14:01
-
-
Save ncreated/e7959cbdded284bc3f22cce00ebffc7c 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
| import RxSwift | |
| final class NetworkToggleStorage: ToggleStorage { | |
| // MARK: - Properties | |
| private var value: Bool | |
| // MARK: - Initializers | |
| init(value: Bool) { | |
| self.value = value | |
| } | |
| // MARK: - Public | |
| func read() -> Observable<Bool> { | |
| return Observable.just(value) | |
| .delay(3, scheduler: MainScheduler.instance) | |
| } | |
| func save(value: Bool) -> Observable<Void> { | |
| let simulateError = shouldFail() | |
| return Observable.just(()) | |
| .delay(1, scheduler: MainScheduler.instance) | |
| .flatMap { _ -> Observable<Void> in | |
| if simulateError { | |
| return .error(NetworkToggleStorageError.savingError) | |
| } else { | |
| return .just() | |
| } | |
| } | |
| .do(onNext: { [weak self] in | |
| if !simulateError { | |
| self?.value = value // update saved value | |
| } | |
| }) | |
| } | |
| // MARK: - Private | |
| private var count = 0 | |
| private func shouldFail() -> Bool { | |
| count += 1 | |
| return count % 3 == 0 // fail every 3 saves | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment