Mobile Dev.
10/04/2022, 2:33 PMclass TestRepo {
suspend fun test(): Int {
delay(5000)
return 10
}
}
and i'm trying to use test method in my ios application.
class ContentViewModel : ObservableObject {
@Published var training: Training_? = nil
@Published var k: String? = nil
@Published var isLoading = false
func fetchData() {
self.isLoading = true
TestRepo().test { vl, err in
self.isLoading = false
self.training = Training_.companion.doInit()
}
}
}
but when i try app in mobile phone i get these error on the xcode. i fix this issue with using DispatchQueue.main.async, is there any other way to fix this issue without using DispatchQueue ?hfhbd
10/04/2022, 3:45 PMhfhbd
10/04/2022, 4:14 PMMobile Dev.
10/04/2022, 4:15 PM@MainActor class ContentViewModel : ObservableObject {
@Published var training: Training_? = nil
@Published var k: String? = nil
@Published var isLoading = false
func fetchData() {
self.isLoading = true
TestRepo().test { vl, err in
self.isLoading = false
self.training = Training_.companion.doInit()
}
}
}
hfhbd
10/04/2022, 4:19 PMtest
is a suspending function, and the callback runs on another thread, usually a background thread. So you have to run this callback on the main thread. One option: extract the callback and add the annotation @MainActor on this function only:
class ContentViewModel : ObservableObject {
@Published var training: Training_? = nil
@Published var k: String? = nil
@Published var isLoading = false
func fetchData() {
self.isLoading = true
TestRepo().test { vl, err in
updateData(vl, err)
}
}
@MainActor
func updateData(vl, error) {
self.isLoading = false
self.training = Training_.companion.doInit()
}
}