Resonance Blog 5. Async/Await for me
Hi, I’m Marko, (mostly) an iOS developer and this is a somewhat weekly list of interesting articles, books, podcasts, music, and videos that I come across during the week that helps me grow or resonate with me in some way. I hope you enjoy it and find something useful here.
---
Async/Await for me
This week I have been doing some research about Apple’s new concurrency system and most helpful articles that I found were on SwiftBySundell and AvanderLee blogs.
I have started to implement some of the basic concepts like async/await and Tasks but one day I hit the wall with the issue that my UI code was executed on Background thread even if I set this function to be @MainActor. I started reading all again and find solution in the bottom of the post Using the MainActor attribute to automatically dispatch UI updates on the main queue | Swift by Sundell:
One thing that’s very important to point out, though, is that all of this only works when we’re using Swift’s new concurrency system. So when using other concurrency patterns, for example completion handlers, then the @MainActor attribute has no effect
Basically, just putting MainActor and hoping it will be executed on Main thread will not work! :)
One article that get me a best introduction about new Swift concurrency is Async await in Swift explained with code examples - SwiftLee. Here we have also a listo of most common problems when we are switching to the new concurrency system and also steps to do it.
iOS related articles:
More good tutorials on this topic I have found on Discover Concurency page and MainActor usage in Swift explained to dispatch to the main thread
iOS Tips:
- I got one tip that is related to this Concurrency (and with any other new framework or topic) in this podcast episode Stacktrace: 162: “Hanging on the cliff for a whole week” on Apple Podcasts. It says that we should try to implement new things in our Unit tests so we get better understanding of the topic and then it will get easier to use it in the production code
- Also one tip on this topic, how to use Task.sleep Delaying an asynchronous Swift Task | Swift by Sundell:
Task {
// Delay the task by 1 second:
try await Task.sleep(nanoseconds: 1_000_000_000)
// Perform our operation
}
I would love to hear from you at @MobileCoding, LinkedIn or via email.