Created
December 21, 2022 02:14
-
-
Save KaneBuckthorpe/38ba9d7adfd7d6bf98bcbd58ef06dd69 to your computer and use it in GitHub Desktop.
AsyncView
This file contains hidden or 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
enum AsyncResult<Data> { | |
case loading | |
case success(Data) | |
case failure(Error) | |
} |
This file contains hidden or 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
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