Skip to content

Instantly share code, notes, and snippets.

@bocato
Last active April 19, 2022 10:00
Show Gist options
  • Save bocato/5b52d2e04c821cdb1f0431b8bfe161e4 to your computer and use it in GitHub Desktop.
Save bocato/5b52d2e04c821cdb1f0431b8bfe161e4 to your computer and use it in GitHub Desktop.
/// 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