비동기 작업에서는 중요한 것 중 하나가 ⭐️스레드 (thread)⭐️를 잘 고려하는 것이다!
Swift Combine의 Operator 에서 Scheduler를 파라미터로 사용하면,
무거운 작업을 메인스레드가 아닌 다른 스레드에서 작업할수 있다!
subscribe(on: )
: publisher 가 어느 스레드에서 수행할지 결정
➞ 무거운 작업은 메인스레드가 아닌 다른 스레드에서 작업할수 있게 도와줌
receive(on: )
: operator, subscriber 가 어느 스레드에서 수행할지 결정
➞ UI 업데이트에 필요한 데이터를 메인스레드에서 받을수 있게 도와줌
let arrPublisher = [1, 2, 3].publisher
let queue = DispatchQueue(label: "custom")
let subscription = arrPublisher
// operator
.subscribe(on: queue) // custom thread에서 진행
.map{ value -> Int in
print("transform: \(value), thread: \(Thread.current)")
return value
}
// subscriber
.receive(on: DispatchQueue.main) // main thread에서 진행
.sink { value in
print("Receive Value: \(value), thread: \(Thread.current)")
}
Operator에서 무거운 작업을 수행한다고 가정했을 때,
custom thread (number=7)에서 무거운 작업을 수행하고,
main thread(number=1)에서 UI 업데이트 등의 작업을 수행한다 :)