Forked from christianselig/swift-async-await-example.swift
Created
April 10, 2022 15:57
-
-
Save codeactual/a3b70167480079da2bb9eb9f4c5a728d to your computer and use it in GitHub Desktop.
Some questions about async await threading in Swift's new concurrency model.
This file contains hidden or 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
| class ViewController: UIViewController { | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| Task { | |
| // 1️⃣❓ UIViewController is in a MainActor context, so this Task | |
| // will inherit that, so the following pretend expensive call will | |
| // be on the main thread and likely block? | |
| ExpensiveOperationPerformer.doExpensiveLoopAndPrint() | |
| } | |
| Task.detached { | |
| // 2️⃣❓ Is this guaranteed to be off the main thread, so perhaps a | |
| // better way to do a one-off, expensive operation? If it's not | |
| // guaranteed, how would I ensure that? Wrap it in an actor | |
| // instead of a class? What if it's not my class/I can't | |
| // change the code? | |
| ExpensiveOperationPerformer.doExpensiveLoopAndPrint() | |
| } | |
| Task { | |
| ExpensiveOperationPerformer.printSomeNetworkData() | |
| } | |
| } | |
| } | |
| class ExpensiveOperationPerformer { | |
| @MainActor | |
| static func printSomeNetworkData() async throws { | |
| let url = URL(string: "https://example.com/example.json")! | |
| // 3️⃣❓ Will this time consuming network call be guaranteed to NOT | |
| // execute on main, despite the MainActor context? Or will it block? | |
| let (data, response) = try await URLSession.data(for: url) | |
| print(data) | |
| } | |
| static func doExpensiveLoopAndPrint() async { | |
| let upperEnd = 9_999_999_999 | |
| var sum = 0 | |
| for i in 0 ..< upperEnd { | |
| sum += 1 | |
| } | |
| print(sum) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment