Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created July 21, 2020 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/520fe5ef85238107744a07c8ed234279 to your computer and use it in GitHub Desktop.
Save davbeck/520fe5ef85238107744a07c8ed234279 to your computer and use it in GitHub Desktop.
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