Created
October 3, 2019 20:51
-
-
Save serhatsezer/06e6d010302becbf2bf94c1fe1c5e5ae to your computer and use it in GitHub Desktop.
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
import UIKit | |
protocol ViewModelType { | |
} | |
protocol Service { | |
func request(_ path: String, completion: @escaping ([String]) -> Void) | |
} | |
struct MainViewModel: ViewModelType { | |
private(set) var service: Service | |
init(_ service: Service) { | |
self.service = service | |
} | |
func getMainArticles(completion: @escaping ([String]) -> Void) { | |
service.request("/path/articles", completion: completion) | |
} | |
func articlesLoaded(_ articles: [String]) { | |
} | |
} | |
class MainViewController: UIViewController { | |
enum State { | |
case loading | |
case loaded([String]) | |
case error | |
case no | |
} | |
private(set) var viewModel: MainViewModel | |
private let indicator = UIActivityIndicatorView(frame: .zero) | |
private let tableView = UITableView(frame: .zero) | |
private var state: State = .no { | |
didSet { | |
switch state { | |
case .loading: | |
indicator.startAnimating() | |
case .loaded(let articles): | |
viewModel.articlesLoaded(articles) | |
tableView.reloadData() | |
indicator.stopAnimating() | |
case .error: | |
print("Show error state!") | |
case .no: | |
print("This is the default state") | |
} | |
} | |
} | |
init(_ viewModel: MainViewModel) { | |
self.viewModel = viewModel | |
super.init(nibName: nil, bundle: nil) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.addSubview(indicator) | |
view.addSubview(tableView) | |
} | |
// triggered somewhere | |
private func callArticles() { | |
state = .loading | |
viewModel.getMainArticles { [weak self] articles in | |
self?.state = .loaded(articles) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment