Post

Replies

Boosts

Views

Activity

Reply to Combine with UITableView
I guess in your case I would bind directly the response from your API to the model, so u can react to it. In your API you could send the publisher directly, and drive it across the view model to the actual view. import Combine class APIClient: NSObject { var cancellable: AnyCancellable? let sharedSession = URLSession.shared func fetchData(urlStr: String) -> AnyPublisher<[MyModel], Error> { guard let url = URL(string: urlStr) else { return } let publisher = sharedSession.dataTaskPublisher(for: url) cancellable = publisher .tryMap { [unowned self] result in let decoder = JSONDecoder() return try decoder.decode([MyModel].self, from: result.data) } .eraseToAnyPublisher() } } import Foundation class ViewModel: NSObject { @IBOutlet var apiClient: APIClient! func getGitData() -> AnyPublisher<[MyModel], Error> { let urlStr = "https://api.github.com/repos/ReactiveX/RxSwift/events" return apiClient.fetchData(urlStr: urlStr) } } import UIKit import Combine class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Variables var cancellables: [AnyCancellable] var viewModel: ViewModel! @Published var models = [MyModel]() // MARK: - IBOutlet @IBOutlet weak var tableView: UITableView! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() viewModel.getGitData() .sink { completion in guard case .failure(let error) = completion else { return } print(error) } receiveValue: { (result) in DispatchQueue.main.async { [weak self] models in guard let strongSelf = self else { return } strongSelf.models = models } } .store(on: $cancellables) $models() .sink { _ in self.tableView.reloadData() } .store(on: $cancellables) } // MARK: - TableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") let dataModel = models[indexPath.row] cell?.textLabel?.text = dataModel.id cell?.detailTextLabel?.text = dataModel.type return cell! } }
Oct ’22