Skip to content

Instantly share code, notes, and snippets.

@eilonkr
Last active November 29, 2020 20:44
Show Gist options
  • Save eilonkr/f42663a016ec03f7215762b6f0bf4a50 to your computer and use it in GitHub Desktop.
Save eilonkr/f42663a016ec03f7215762b6f0bf4a50 to your computer and use it in GitHub Desktop.
import UIKit
import Combine
class LibraryViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
private var tokens = [AnyCancellable]()
// We're making the viewModel property lazy so it can access `self` during initialization.
private lazy var viewModel = LibraryViewModel(collectionView: collectionView)
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
}
private func configureCollectionView() {
// Assign the data source and delegate
collectionView.dataSource = viewModel.makeDataSource()
collectionView.delegate = viewModel
// Layout stuff
...
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nav = segue.destination as? UINavigationController, let dest = nav.viewControllers.first as? NewNoteViewController else { fatalError() }
// I chose to use Combine's Publisher pattern for communication, but feel free to use any of your other favorite communication patterns such as delegates or closures.
dest.notePublisher.sink { [unowned self] note in
// Add the note!
viewModel.add([note])
}
.store(in: &tokens)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment