Skip to content

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

License

Notifications You must be signed in to change notification settings

heroesofcode/ViewState

Repository files navigation

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", exact: "2.0.1")
    ],
    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.

License

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

About

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

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •