Last active
May 20, 2021 20:47
-
-
Save ahmedk92/f8f2438b3e556785ceb60cf6f33879ac to your computer and use it in GitHub Desktop.
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
class ViewModel { | |
private let repository: Repository | |
private(set) var data: Data? | |
var updateUi: (() -> Void)? | |
func viewDidLoad() { | |
repository.getData(cachePolicy: .cacheThenNetwork) { [weak self] data in | |
self?.data = data | |
self?.updateUi?() | |
} | |
} | |
} | |
enum CachePolicy { | |
case cacheOnly, cacheThenNetwork, networkOnly | |
} | |
protocol Repository: AnyObject { | |
func getData(cachePolicy: CachePolicy, completion: @escaping (Result<Data, Error>) -> Void) | |
} | |
enum RepositoryError: Error { | |
case emptyCacheError | |
} | |
class DefaultRepository: Repository { | |
private let localDataSource: LocalDataSource | |
private let remoteDataSource: RemoteDataSource | |
func getData(cachePolicy: CachePolicy, completion: @escaping (Result<Data, Error>) -> Void) { | |
switch cachePolicy { | |
case .cacheOnly: | |
if let data = localDataSource.getData() { | |
completion(.success(data)) | |
} else { | |
completion(.failure(RepositoryError.emptyCacheError)) | |
} | |
case .cacheThenNetwork: | |
if let data = localDataSource.getData() { | |
completion(.success(data)) | |
} | |
remoteDataSource.getData(completion: completion) | |
case .networkOnly: | |
remoteDataSource.getData(completion: completion) | |
} | |
} | |
} | |
protocol LocalDataSource { | |
func getData() -> Data? | |
} | |
protocol RemoteDataSource { | |
func getData(completion: @escaping (Result<Data, Error>) -> Void) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment