Skip to content

Instantly share code, notes, and snippets.

@ncreated
Created August 10, 2017 14:01
Show Gist options
  • Save ncreated/e7959cbdded284bc3f22cce00ebffc7c to your computer and use it in GitHub Desktop.
Save ncreated/e7959cbdded284bc3f22cce00ebffc7c to your computer and use it in GitHub Desktop.
Medium blogpost snippet
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