Skip to content

Instantly share code, notes, and snippets.

@zafarivaev
Last active January 19, 2022 16:48
Show Gist options
  • Save zafarivaev/e5e709f72e6dbb02a192b00a804b3928 to your computer and use it in GitHub Desktop.
Save zafarivaev/e5e709f72e6dbb02a192b00a804b3928 to your computer and use it in GitHub Desktop.
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