๊ฐ๋
ํน์ ์์ ์ด ์ ์ญ์ ์ผ๋ก ๋จ์ผ ์ค๋ ๋์์ ์คํ๋๋๋ก ๋ณด์ฅํ๋ ์ฅ์น
- ์ฐ๋ฆฌ๋
@MainActor
๋ผ๋ ํค์๋๋ง ์ถ๊ฐํ๊ฒ ๋๋ฉด main thread์์ ๋์ํ๋ค๋ ๊ฒ์ ๋ณด์ฅํ ์ ์๋ค. - ์ด๋ป๊ฒ ๊ฐ๋ฅํ ๊ฒ์ผ๊น?
MainActor
@globalActor
final public actor MainActor: GlobalActor {
public static let shared: MainActor
@inlinable nonisolated final public var unownedExecutor: UnownedSerialExecutor { get }
@inlinable public static var sharedUnownedExecutor: UnownedSerialExecutor { get }
@inlinable nonisolated final public func enqueue(_ job: UnownedJob)
public typealias ActorType = MainActor
}
- MainActor๋ GlobalActor๋ฅผ ์ฑํํ๊ณ ์์์ ํ์ธํ ์ ์๋ค.
- ํด๋น actor๋ ์์ ์ ๊ณ ์ ํ ์คํํ๋ฆ์ ๊ฐ์ง๊ณ ์์ผ๋ฉฐ, ์ ์ญ์ ์ผ๋ก ํด๋น ์คํํ๋ฆ์ ํน์ ํจ์๋ ํ๋กํผํฐ์ ์ ์ธํ์ฌ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ๋ค.
Customization
@globalActor actor UserProfileActor {
static var shared = UserProfileActor()
}
- ๊ทธ๋ ๋ค๋ฉด ๊ณ ์ ์ ์คํํ๋ฆ์ ๊ฐ์ง๋ Actor ์ญ์ ๋ง๋ค ์ ์์ ๊ฒ์ด๋ค.
Usage
@MainActor
final class UserViewModel {
func updateProfilePhoto() {
print("Update the profile photo done on MainThread: \(Thread.isMainThread)")
print("Update the profile photo done on Thread: \(Thread.current)")
}
@UserProfileActor
func fetchProfilePhoto() async {
print("Fetch the profile photo done on MainThread: \(Thread.isMainThread)")
print("Fetch the profile photo done on Thread: \(Thread.current)")
await updateProfilePhoto()
}
}
Fetch the profile photo done on MainThread: false
Fetch the profile photo done on Thread: <NSThread: 0x600000c34940>{number = 7, name = (null)}
Update the profile photo done on MainThread: true
Update the profile photo done on Thread: <_NSMainThread: 0x600000c280c0>{number = 1, name = main}
- ๋ ๊ฐ ์ด์์ Annotation์ ์ค์ ํ๊ณ ์คํํ์ ๋์ ๊ฒฐ๊ณผ์ด๋ค.
- ํจ์์ ์ค์ ํ๋ ๊ฒ์๋ฐ๋ผ ์คํํ๋ฆ์ด ๋ฐ๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.