-
[UIKit] MVVM(Combine) 과 UITableViewDiffableDataSource 같이 써보기Swift/UIKit 2022. 11. 28. 14:17
Async/Await, MVVM, Combine, TableDiffableDataSource 를 같이 사용해보았다
VC 에서 TableView와 DataSource 를 들고 있고
MVVM 에서 실제 Data 와 FetchRequest 를 요청하는 함수를 실행한다
APIClient 는 실제로 요청을 보낸다
// ViewController enum Section { case main } var tableView: UITableView! var dataSource: UITableViewDiffableDataSource<Section, Person>! private let viewModel = ViewModel() private var cancelBag = Set<AnyCancellable>() func configureTableView() { tableView = UITableView(frame: view.bounds) view.addSubview(tableView) tableView.register(PersonCell.self, forCellReuseIdentifier: PersonCell.reuseID) } func updateData(on people: [Person]) { var snapshot = NSDiffableDataSourceSnapshot<Section, Person>() snapshot.appendSections([.main]) snapshot.appendItems(people) DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.dataSource.apply(snapshot, animatingDifferences: true) } } func configureDataSource() { dataSource = UITableViewDiffableDataSource<Section, Person>(tableView: tableView, cellProvider: { tableView, indexPath, person in let cell = tableView.dequeueReusableCell(withIdentifier: PersonCell.reuseID) as! PersonCell cell.set(person: person) return cell }) } func setViewModel() { viewModel.$people .receive(on: DispatchQueue.main) .sink { [weak self] people in guard let self = self else { return } self.updateData(on: people) } .store(in: &cancelBag) }
// ViewModel @Published var people: [Person] = [] func fetchStarwarsPeople() { Task { do { people = try await APIClient().getPeople() } catch NetworkError.invalidURL { print("Invalid URL ERROR!") } } }
'Swift > UIKit' 카테고리의 다른 글
[UIKit] cell 안에서 버튼이 실행이 안될때 (0) 2022.12.02 [UIKit] addSubview 리팩토링 해보기 (0) 2022.11.28 [UIKit] UICollectionViewDiffableDataSource에 대해 알아보자 (0) 2022.11.27 [UIKit] frame vs bounds (0) 2022.11.25 [UIKit] setNavigationBarHidden vs isNavigationBarHidden (0) 2022.11.21