Skip to content

Instantly share code, notes, and snippets.

Created Jul 21, 2020
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.isLoding = true
observer = publisher
.sink { completion in
switch completion {
case .failure(let error):
self.error = error
case .finished:
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 {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment