Last active
January 19, 2022 16:48
-
-
Save zafarivaev/e5e709f72e6dbb02a192b00a804b3928 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
import UIKit | |
import Combine | |
... | |
enum State: String { | |
case initial = "Initial" | |
case loading = "Loading" | |
case loadedSuccessfully = "Success" | |
case loadingFailed = "Failure" | |
} | |
class ViewController: UIViewController { | |
... | |
@Published var state: State = .initial | |
override func viewDidLoad() { | |
... | |
} | |
private func bindAvatarToImageView() { | |
getAvatarFromTheServer() | |
.handleEvents(receiveSubscription: { [weak self] in | |
print("Subscribed", $0) | |
// 1 | |
self?.state = .loading | |
}, receiveOutput: { | |
... | |
}, receiveCompletion: { | |
... | |
}) | |
.delay(...) | |
.retry(...) | |
.receive(...) | |
.sink(receiveCompletion: { [weak self] completion in | |
switch completion { | |
case let .failure(error): | |
print("Finished with error: \(error)") | |
// 2 | |
self?.state = .loadingFailed | |
case .finished: | |
print("Finished") | |
} | |
}, receiveValue: { [weak self] image in | |
self?.imageView.image = image | |
// 3 | |
self?.state = .loadedSuccessfully | |
}) | |
.store(in: &cancellables) | |
} | |
private func getAvatarFromTheServer() -> AnyPublisher<UIImage, Error> { | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment