Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.