-
-
Save Dimillian/f943a7a08b3741b1c1e5023404a4280e to your computer and use it in GitHub Desktop.
Custom Lazy Loading
This file contains hidden or 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 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 | |
} | |
} | |
} | |
} |
This file contains hidden or 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 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