Skip to content

Instantly share code, notes, and snippets.

@bannzai
Created May 25, 2024 11:04
Show Gist options
  • Save bannzai/35e4fbd4b6dd72ee8dafda0c2683fb98 to your computer and use it in GitHub Desktop.
Save bannzai/35e4fbd4b6dd72ee8dafda0c2683fb98 to your computer and use it in GitHub Desktop.
import SwiftUI
struct AsyncAction<Content: View>: View {
@State var isLoading = false
@State var task: @Sendable @MainActor () async -> Void
@ViewBuilder let content: (Bool, @escaping () -> Void) -> Content
var body: some View {
content(isLoading, {
if isLoading {
return
}
isLoading = true
Task { @MainActor in
await task()
isLoading = false
}
})
}
}
@bannzai
Copy link
Author

bannzai commented May 25, 2024

Example:

AsyncAction {
  do {
     try await doSomething1()
     try await doSomething2()
  } catch {
    self.error = error
  }
} content: { isLoading, action in
  Button {
    action()
  } label: {
    Text("Example")
  }
  .loading(isLoading: isLoading)
}
.alert(error: $error)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment