Last active
January 29, 2019 16:39
-
-
Save hmlongco/76e03904f1379b1074ca5c00aab4fdd8 to your computer and use it in GitHub Desktop.
StructStateViewModel
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 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