What is @MainActor and How to use it
MainActor
is a singleton that runs code on the main thread. In more detailed terms, it is an actor whose executor runs code on the main thread, also known as the main thread or UI thread.
There are many use to MainActor
By calling the run
method and passing our code in a closure:
await MainActor.run {
await execute()
}
The second way to use MainActor
is by annotating our code using @MainActor
:
@MainActor
func execute() async {
//....
}
This ensures that our code runs on the main thread. We can also use this notation in classes and task closures.
To indicate that an entire class will perform its operations on the main thread, we do the following:
@MainActor
class MyClass {
// Code here...
}
If we want a specific method not to run on the main thread, we can do so using the nonisolated
modifier:
@MainActor
class MyClass {
func run() { ... }
nonisolated func stop() { ... }
}
In this case, run()
will execute on the main thread, but stop()
will not.
To specify that a task closure will perform its operations on the main thread, we do the following:
Task { @MainActor in
// Code here...
}
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/que-es-main-actor/