How can I call in Swift 6 a normal async function from a MainActor function? I do not want to execute URLRequests on the MainThread
I want to switch from the Main Thread to an async Thread but I have no idea how to do it...
This code doesn't work and throws the following error: Sending 'self.service' risks causing data races
import SwiftUI
struct CustomView: View {
private let viewModel: CustomViewModel = CustomViewModel()
var body: some View {
Text("HELLO")
.task {
Task {
await viewModel.getDataFromBackend()
}
}
}
}
@Observable
final class CustomViewModel {
private let service: CustomService = DefaultCustomService()
@MainActor func getDataFromBackend() async {
// Updating UI on Main-Thread
// This shouldn't run on the Main Thread!
await service.provideBackendData()
}
}
protocol CustomService {
func provideBackendData() async
}
struct DefaultCustomService: CustomService {
func provideBackendData() async {
// Async Stuff which shouldn't run on Main-Thread
}
}
You can just add
protocol CustomService: Sendable {
To remove the error.
In order to safely make something Sendable you should meet all of these official requirements
https://developer.apple.com/documentation/swift/sendable
Unofficially any reference types should also be marked final so the user cant create unsafe mutating children.
You can also use actor and globalActor to make something Sendable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With