Created
July 21, 2020 03:42
-
-
Save davbeck/520fe5ef85238107744a07c8ed234279 to your computer and use it in GitHub Desktop.
Loader for SwiftUI derived data
This file contains 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
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