Last active
January 8, 2024 22:41
-
-
Save denissimon/3b8c5a02ad2ce5f290f3fbecdbfb2fda to your computer and use it in GitHub Desktop.
Example of cell-to-cellViewModel binding using the SwiftEvents library (https://github.com/denissimon/SwiftEvents)
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
//// MusicPlayerViewController: UIViewController | |
private var viewModel: MusicPlayerViewModel! | |
func tableView(_ tableView: UITableView, | |
cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
guard let cell = /* getting cell */ | |
configure(cell: cell, with: viewModel.songViewModels[indexPath.row]) | |
return cell | |
} | |
private func configure(cell: SongViewCell, with cellViewModel: SongViewModel) { | |
/* configuring cell */ | |
cell.update(mode: cellViewModel.songMode.value, animated: false) | |
cell.unbindable = cellViewModel.songMode | |
cellViewModel.songMode.bind(cell) { [weak cell] in cell?.update(mode: $0, animated: true) } | |
} | |
//// SongViewCell: UITableViewCell | |
var unbindable: Unbindable? | |
override func prepareForReuse() { | |
super.prepareForReuse() | |
unbindable?.unbind(self) | |
} | |
func update(mode: SongMode, animated: Bool) { | |
/* updating the cell’s view */ | |
} | |
//// SongViewModel | |
var songMode: Observable<SongMode> = Observable(.unselected) | |
/* | |
The MusicPlayerViewController binds each SongViewCell to its SongViewModel’s observable property `songMode`. | |
When the `songMode` in some SongViewModel is updated, the associated SongViewCell will be notified | |
and its `update(mode:animated:)` handler will be called. | |
Using the `Unbindable` protocol, we pass an Observable reference to SongViewCell and `unbind` when reusing a cell | |
(prepareForReuse()). This way, there will only be 1 observer for each Observable, otherwise they would be binded again | |
and accumulated along with the scrolling of the table. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment