Indicating which context we are

Updated
Aug 8, 2022 3:41 PM
Created
Aug 8, 2022 3:12 PM
Tags
ConcurrencySwift
Attributes

@MainActor
private func runUI() {

}

func perform() {
  Task {
		// ❓ Which thread runs on?
    // Runs on background even if `perform` runs on main-thread
    await runUI()
  }
  DispatchQueue.global().async {

    Task {
      // ❓ Which thread runs on?
      await runUI()

    }
  }
  
  DispatchQueue.main.async {
    
    Task {
      // ❓ Which thread runs on?
			// ❓ Why don't need await?
			// Don't need await because DispatchQueue.main.async supports main-actor-isolated, this case Task inherits current isolation. so runsUI runs synchronously without awaiting. (but maybe event-loop runs loop technically) 
      runUI()
      
    }
  }
}

Thanks to UIKit, SwiftUI, and any other libraries are compatible with Concurrency, we could write code as usual. Although, this behavior hides how swift-concurrency exactly works in compile-time.

Primitively, we can not call main-actor-isolated method from non-isolated method just like func without any other attributes. Because that method don’t know which thread triggers it. But we can do that inside UIViewController or SwiftUI.View which is why compatible with MainActor implicitly.