Skip to content

Instantly share code, notes, and snippets.

@thepearl
Created January 14, 2021 17:26
Show Gist options
  • Save thepearl/733e0389dfeffbb5c4eea790c9ad0c42 to your computer and use it in GitHub Desktop.
Save thepearl/733e0389dfeffbb5c4eea790c9ad0c42 to your computer and use it in GitHub Desktop.
Final version of ViewModel
import UIKit
import Combine
class ViewModel
{
var cancellables: Set<AnyCancellable> = []
init()
{
$keyWordSearch.receive(on: RunLoop.main).debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.sink { (_) in
self.fetchMovies()
}.store(in: &cancellables)
}
let serviceProvider = Service.sharedInstance
@Published var keyWordSearch: String = ""
var diffableDataSource: MoviesTableViewDiffableDataSource!
var snapshot = NSDiffableDataSourceSnapshot<String?, Result>()
func fetchMovies()
{
serviceProvider.fetchFilms(for: keyWordSearch) { (results) in
guard self.diffableDataSource != nil else { return }
self.snapshot.deleteAllItems()
self.snapshot.appendSections([""])
if results.isEmpty
{
self.diffableDataSource.apply(self.snapshot, animatingDifferences: true)
return
}
self.snapshot.appendItems(results, toSection: "")
self.diffableDataSource.apply(self.snapshot, animatingDifferences: true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment