-
-
Save laevandus/a57d11d37aa8306aa90c9ee6a0a4a862 to your computer and use it in GitHub Desktop.
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
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