Last active
August 20, 2020 17:52
-
-
Save dmytro-anokhin/9420ca667ac85c94d604dba7d456256b 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
final class DecodableRemoteContent<Value, Decoder> : RemoteContent where Value : Decodable, | |
Decoder : TopLevelDecoder, | |
Decoder.Input == Data | |
{ | |
unowned let urlSession: URLSession | |
let url: URL | |
let type: Value.Type | |
let decoder: Decoder | |
init(urlSession: URLSession = .shared, url: URL, type: Value.Type, decoder: Decoder) { | |
self.urlSession = urlSession | |
self.url = url | |
self.type = type | |
self.decoder = decoder | |
} | |
@Published private(set) var loadingState: RemoteContentLoadingState<Value> = .initial | |
func load() { | |
// Set state to in progress | |
loadingState = .inProgress | |
// Start loading | |
cancellable = urlSession | |
.dataTaskPublisher(for: url) | |
.map { | |
$0.data | |
} | |
.decode(type: type, decoder: decoder) | |
.map { | |
.success($0) | |
} | |
.catch { | |
Just(.failure($0)) | |
} | |
.receive(on: RunLoop.main) | |
.assign(to: \.loadingState, on: self) | |
} | |
func cancel() { | |
// Reset loading state | |
loadingState = .initial | |
// Stop loading | |
cancellable?.cancel() | |
cancellable = nil | |
} | |
private var cancellable: AnyCancellable? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment