Last active
January 29, 2019 16:40
-
-
Save hmlongco/ca9d1840bc68d4e7e209d51d985cc6ec to your computer and use it in GitHub Desktop.
EnumeratedStateViewModel
This file contains 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
class EnumeratedStateViewModel { | |
public let state: Observable<State> | |
enum State: Equatable { | |
case initial | |
case loading | |
case loaded(UIImage) | |
case empty(String) | |
case error(String) | |
case cancel | |
} | |
private let privateState = BehaviorRelay(value: State.initial) | |
private let disposeBag = DisposeBag() | |
init() { | |
self.state = privateState.observeOn(MainScheduler.instance) | |
} | |
public func load(_ id: String) { | |
privateState.accept(.loading) | |
fetchData() | |
.subscribe(onSuccess: { [weak self] (image) in | |
if image.size.width == 0 { | |
self?.privateState.accept(.empty("Nothing to see here, move along.")) | |
} else { | |
self?.privateState.accept(.loaded(image)) | |
} | |
}, onError: { [weak self] (error) in | |
self?.privateState.accept(.error(error.localizedDescription) | |
}) | |
.disposed(by: disposeBag) | |
} | |
public func cancel() { | |
privateState.accept(.cancel) | |
} | |
private func fetchData() -> Single<UIImage> { | |
return Single.just(UIImage()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment