Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created June 28, 2019 10:27
Show Gist options
  • Save chriseidhof/e56128e4421ab59504153fb5f575fd0b to your computer and use it in GitHub Desktop.
Save chriseidhof/e56128e4421ab59504153fb5f575fd0b to your computer and use it in GitHub Desktop.
Custom Lazy Loading
import Foundation
import SwiftUI
import Combine
import TinyNetworking
final class RemoteValue<A>: BindableObject {
let didChange = MyPublisher()
let endpoint: Endpoint<A>
var value: A? {
didSet {
DispatchQueue.main.async {
self.didChange.send()
}
}
}
init(_ endpoint: Endpoint<A>, initial: A? = nil) {
self.endpoint = endpoint
self.value = initial
didChange.onSubscribe = { [weak self] in
self?.reload()
}
}
func reload() {
print("Loading \(endpoint)")
URLSession.shared.load(endpoint) { result in
switch result {
case .failure:
()
// self.value = nil
case .success(let x): self.value = x
}
}
}
}
import Foundation
import Combine
import Register // from https://github.com/chriseidhof/register
class MySubscription: Subscription {
let cleanup: () -> ()
init(_ cleanup: @escaping () -> ()) {
self.cleanup = cleanup
}
func request(_ demand: Subscribers.Demand) {
assert(demand == .unlimited) // todo we don't support other demands yet
}
func cancel() {
cleanup()
}
deinit {
cleanup()
}
}
class MyPublisher: Publisher {
typealias Output = ()
typealias Failure = Never
var onSubscribe: () -> () = { }
var subscribers: Register<AnySubscriber<(), Never>> = Register() {
didSet {
if oldValue.isEmpty && !subscribers.isEmpty {
onSubscribe()
}
}
}
func receive<S>(subscriber: S) where S : Subscriber, S.Failure == Never, S.Input == () {
let token = subscribers.add(AnySubscriber(subscriber))
let subscription = MySubscription() { [weak self] in
self?.subscribers.remove(token)
}
subscriber.receive(subscription: subscription)
}
func send() {
for s in subscribers.values {
let demand = s.receive(())
// todo we don't do anything with demand yet
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment