Hello folks, i want to ask something in my kmm pr...
# multiplatform
m
Hello folks, i want to ask something in my kmm project i have this line of code
Copy code
class TestRepo {
    suspend fun test(): Int {
        delay(5000)
        return 10
    }
}
and i'm trying to use test method in my ios application.
Copy code
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 ?
h
Use Swift 5.5 and @MainActor to switch back to the main thread
What do you mean by: didn't work? What did you try?
m
I add @MainActor to view model like below
Copy code
@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()
    }
  }
   
}
h
Yeah, this won't work.
test
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:
Copy code
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()
 }
}