Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created September 4, 2022 10: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 laevandus/a57d11d37aa8306aa90c9ee6a0a4a862 to your computer and use it in GitHub Desktop.
Save laevandus/a57d11d37aa8306aa90c9ee6a0a4a862 to your computer and use it in GitHub Desktop.
struct PrepareAsyncViewData: ViewModifier {
@State var hasPrepared = false
@State var task: Task<Void, Never>?
let action: (() async -> Void)
func body(content: Content) -> some View {
content
.onAppear {
guard !hasPrepared else { return }
guard task == nil else { return }
task = Task {
await action()
hasPrepared = true
}
}
.onDisappear {
task?.cancel()
task = nil
}
}
}
extension View {
func prepare(perform action: @escaping () async -> Void) -> some View {
modifier(PrepareAsyncViewData(action: action))
}
}
struct OtherView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
VStack {
// redacted
}
.prepare {
await viewModel.prepare()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment