Skip to content

Instantly share code, notes, and snippets.

@davbeck

davbeck/Loader.swift

Created Jul 21, 2020
Embed
What would you like to do?
Loader for SwiftUI derived data
class Loader<Output>: ObservableObject {
@Published var isLoding: Bool = false
@Published var error: Swift.Error?
@Published var value: Output?
private var observer: AnyCancellable?
func load<P: Publisher>(_ publisher: P) where P.Output == Output {
self.observer?.cancel()
self.isLoding = true
observer = publisher
.sink { completion in
switch completion {
case .failure(let error):
self.error = error
case .finished:
break
}
self.isLoding = false
} receiveValue: { output in
self.value = output
}
}
}
struct Content: View {
var prop: Int
@StateObject var loader: Loader<String>()
var body: some View {
Text(loader.value ?? loader.error?.localizedDescription ?? "Loading...")
.onAppear {
loader.load(Just("\(prop)"))
}
.id(prop)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment