Created
          January 14, 2021 17:26 
        
      - 
      
 - 
        
Save thepearl/733e0389dfeffbb5c4eea790c9ad0c42 to your computer and use it in GitHub Desktop.  
    Final version of ViewModel
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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