ViewState

1.6.0

ViewState is a library written in Swift for iOS, tvOS, macOS & watchOS. It returns the results for each state
heroesofcode/ViewState

What's New

2023-12-14T03:38:27Z

What's new?

  • From this version onwards, loadingObserver will be optional

CI SPM compatible License

Overview

A View State library to return the results for each state

Usage

  • 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 😃.

Installation

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"]),
    ]
)

Contributing

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.

Contributors

License

ViewState is released under the MIT license. See LICENSE for details.

Description

  • Swift Tools 5.6.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun Dec 15 2024 22:49:24 GMT-1000 (Hawaii-Aleutian Standard Time)