Skip to content

Instantly share code, notes, and snippets.

@devishot
Created December 9, 2016 10:12
Show Gist options
  • Save devishot/7bdbc7304dd97c4e671c8257004184ab to your computer and use it in GitHub Desktop.
Save devishot/7bdbc7304dd97c4e671c8257004184ab to your computer and use it in GitHub Desktop.
iOS MVVM with POP
//: Playground - noun: a place where people can play
import UIKit
protocol PaginatedDataStateProtocol {
var items: [NSObject] { get set }
var page: Int { get set }
var isFetching: Bool { get set }
}
protocol PaginatedDataViewModelProtocol {
associatedtype DataStateType
var state: DataStateType { get set }
mutating func onLoadFirstDataPage()
mutating func onLoadNextDataPage()
func checkLoadNextPage()
}
extension PaginatedDataViewModelProtocol {
mutating func onLoadFirstDataPage() {
var updState = self.state as! PaginatedDataStateProtocol
updState.page = 1
updState.isFetching = true
self.state = updState as! DataStateType
}
mutating func onLoadNextDataPage() {
}
func checkLoadNextPage() {
}
}
// Model
struct CityModel {}
// ViewModel State
struct SelectCityState: PaginatedDataStateProtocol {
var items: [NSObject]
var page: Int
var isFetching: Bool
var selected: NSObject?
var search: String?
}
// ViewModel
struct SelectCityViewModel: PaginatedDataViewModelProtocol {
var state: SelectCityState
init() {
self.state = SelectCityState(items: [], page: 0, isFetching: false, selected: nil, search: nil)
}
}
// View
class ViewController {
var viewModel: SelectCityViewModel! {
didSet {
self.updateView()
}
}
func onClick() {
self.viewModel.onLoadFirstDataPage()
}
private func updateView() {
print(".ViewController.update", self.viewModel.state)
}
}
var vm = SelectCityViewModel()
let vc = ViewController()
vc.viewModel = vm
vc.onClick()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment