Skip to content

Instantly share code, notes, and snippets.

View nalexn's full-sized avatar
😈
Designing software the ruthless way

Alexey Naumov nalexn

😈
Designing software the ruthless way
View GitHub Profile
@nalexn
nalexn / Loadable.swift
Last active July 24, 2020 01:14
A container for a resource requested from the backend
// Copyright © 2019 Alexey Naumov. MIT License
import Foundation
enum Loadable<Value> {
case notRequested
case isLoading(prevValue: Value?)
case loaded(Value)
case failed(Error)
}
class ValueConsumer {
private var subscription1: AnyCancellable?
private var subscription2: AnyCancellable?
private var subscription3: AnyCancellable?
private let mySubject = CurrentValueSubject<Int, Never>(0)
private var myVar: Int = 0
func consumeValues(publisher1, ...) {
subscription1 = publisher1
class ValueConsumer {
private var subscriptions = Set<AnyCancellable>()
private let mySubject = CurrentValueSubject<Int, Never>(0)
private var myVar: Int = 0
func consumeValues(publisher1, ...) {
publisher1
.sink { print("New value: \($0)") }
class ValueConsumer {
private var subscriptions = Set<AnyCancellable>()
private let mySubject = CurrentValueSubject<Int, Never>(0)
private var myVar: Int = 0
func consumeValues(publisher1, ...) {
subscriptions.collect {
publisher1
struct Podcast: Equatable {
let title: String
let previewImage: UIImage
let podcastURL: URL
}
protocol PodcastsService {
func loadPodcasts(completion: (Result<[Podcast], Error>) -> Void)
}
class PodcastsViewModel {
private let service: PodcastsService
let podcasts = BehaviorRelay<[Podcast]>(value: [])
func loadPodcasts() {
service.loadPodcasts { [weak self] result in
let records = result.value ?? []
self?.podcasts.accept(records)
class PodcastCell: UITableViewCell {
func populate(podcast: Podcast) {
textLabel?.text = podcast.title
imageView?.image = podcast.previewImage
}
}
class PodcastsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var viewModel: PodcastsViewModel!
var disposeBag = DisposeBag()
func viewDidLoad() {
super.viewDidLoad()
let cellIdentifier = String(describing: PodcastCell.self)
tableView.register(PodcastCell.self, forCellReuseIdentifier: cellIdentifier)
class PodcastsViewModel {
private let service: PodcastsService
let podcasts = BehaviorRelay<[Podcast]>(value: [])
let isLoading = BehaviorRelay<Bool>(value: false)
let onError = PublishRelay<Error> = PublishRelay()
func loadPodcasts() {
isLoading.accept(true)