Last active
April 19, 2022 10:00
-
-
Save bocato/5b52d2e04c821cdb1f0431b8bfe161e4 to your computer and use it in GitHub Desktop.
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
/// Defines the `SomeRepository` contract. | |
protocol SomeRepositoryProtocol { | |
/// Returns the cached data. | |
var cachedList: [String]? { get } | |
/// Gets the list from service or cache. | |
/// - Parameter completion: returns the list | |
func getList(then completion: @escaping ([String]?) -> Void) | |
} | |
final class SomeRepository: SomeRepositoryProtocol { | |
// MARK: - Dependencies | |
private let session: URLSession | |
private let jsonDecoder: JSONDecoder | |
// MARK: - Properties | |
private(set) var cachedList: [String]? | |
// MARK: - Initialization | |
init( | |
session: URLSession = .shared, | |
jsonDecoder: JSONDecoder = .init() | |
) { | |
self.session = session | |
self.jsonDecoder = jsonDecoder | |
} | |
// MARK: - Public API | |
func getList(then completion: @escaping ([String]?) -> Void) { | |
if let cached = cachedList { | |
completion(cached) | |
return | |
} | |
session.dataTask(with: .init(string: "www.myapi.com/list")!) { [weak self] data, response, error in | |
guard | |
let data = data, | |
let decodedValue = try? self?.jsonDecoder.decode([String].self, from: data) | |
else { | |
completion(nil) | |
return | |
} | |
self?.cachedList = decodedValue | |
completion(decodedValue) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment