Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Last active January 29, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmlongco/76e03904f1379b1074ca5c00aab4fdd8 to your computer and use it in GitHub Desktop.
Save hmlongco/76e03904f1379b1074ca5c00aab4fdd8 to your computer and use it in GitHub Desktop.
StructStateViewModel
class StructStateViewModel {
public let state: Observable<State>
struct State {
var id: String?
var loading = false
var image: UIImage?
var empty: String?
var error: String?
var cancel = false
}
private let privateState = BehaviorRelay(value: State())
private let disposeBag = DisposeBag()
init() {
self.state = privateState.observeOn(MainScheduler.instance)
}
public func load(_ id: String) {
var state = privateState.value
state.id = id
state.loading = true
state.error = nil
state.image = nil
state.empty = nil
privateState.accept(state)
getSomeData()
.subscribe(onSuccess: { [weak self] (image) in
state.loading = false
if image.size.width == 0 {
state.empty = "Nothing to see here, move along."
} else {
state.image = image
}
self?.privateState.accept(state)
}, onError: { [weak self] (error) in
state.error = error.localizedDescription
self?.privateState.accept(state)
})
.disposed(by: disposeBag)
}
public func cancel() {
var state = State()
state.cancel = true
privateState.accept(state)
}
private func getSomeData() -> Single<UIImage> {
return Single.just(UIImage())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment