Skip to content

Instantly share code, notes, and snippets.

@KaneBuckthorpe
Created December 21, 2022 02:14
Show Gist options
  • Save KaneBuckthorpe/38ba9d7adfd7d6bf98bcbd58ef06dd69 to your computer and use it in GitHub Desktop.
Save KaneBuckthorpe/38ba9d7adfd7d6bf98bcbd58ef06dd69 to your computer and use it in GitHub Desktop.
AsyncView
enum AsyncResult<Data> {
case loading
case success(Data)
case failure(Error)
}
struct AsyncView<Data, Content>: View where Content: View {
private let operation: (() async throws -> Data)
private let transition: AnyTransition
@ViewBuilder
private let content: (AsyncResult<Data>) -> Content
@State private var loadState: AsyncResult<Data> = .loading
init(_ operation: @escaping () async throws -> Data, transition: AnyTransition = .identity, @ViewBuilder content: @escaping (AsyncResult<Data>) -> Content) {
self.operation = operation
self.transition = transition
self.content = content
}
var body: some View {
VStack {
content(loadState)
}
.task {
do {
loadState = .success(try await operation())
} catch {
loadState = .failure(error)
}
}
.transition(transition)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment