๊ฐœ๋…

ํŠน์ • ์ž‘์—…์ด ์ „์—ญ์ ์œผ๋กœ ๋‹จ์ผ ์Šค๋ ˆ๋“œ์—์„œ ์‹คํ–‰๋˜๋„๋ก ๋ณด์žฅํ•˜๋Š” ์žฅ์น˜

  • ์šฐ๋ฆฌ๋Š” @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์„ ์„ค์ •ํ•˜๊ณ  ์‹คํ–‰ํ–ˆ์„ ๋•Œ์˜ ๊ฒฐ๊ณผ์ด๋‹ค.
  • ํ•จ์ˆ˜์— ์„ค์ •ํ•˜๋Š” ๊ฒƒ์—๋”ฐ๋ผ ์‹คํ–‰ํ๋ฆ„์ด ๋ฐ”๋€Œ๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์ž‡๋‹ค.

Reference