A View State library to return the results for each state
- In ViewModel calls the states that will return to ViewController
import ViewState
final class ViewModel {
private var viewState = ViewState<Model, APIError>()
private let service = Service()
func fetchData() -> ViewState<Model, APIError> {
viewState.fetchSource {
self.service.getData { [weak self] result in
switch result {
case .success(let response):
self?.viewState.success(data: response)
case .failure(let error):
self?.viewState.error(error: error)
}
}
}
return viewState
}
}
- In the ViewController it calls the ViewModel method and places the states of each one.
import UIKit
import ViewState
final class ViewController: UIViewController {
private let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
private func loadData() {
viewModel.fetchData()
.loadingObserver(onLoading)
.successObserver(onSuccess)
.errorObserver(onFailure)
}
private func onLoading() {
// Event loading
}
private func onSuccess(response: Model) {
// Event success
}
private func onFailure(error: APIError) {
// Event error
}
}
- loadingObserver is optional, you can just use success and error
private func loadData() {
viewModel.fetchData()
.successObserver(onSuccess)
.errorObserver(onFailure)
}
- See a demo below. You can see this demo in our example 😃.
import PackageDescription
let package = Package(
name: "<Your Product Name>",
dependencies: [
.package(url: "https://github.com/heroesofcode/ViewState", .upToNextMajor(from: "1.6.0"))
],
targets: [
.target(
name: "<Your Target Name>",
dependencies: ["ViewState"]),
]
)
To contribute, just fork this project and then open a pull request, feel free to contribute, bring ideas and raise any problem in the issue tab.
ViewState is released under the MIT license. See LICENSE for details.