λΉλκΈ° μμ μ κΈ°λ³Έ λ¨μ
κ·Έλ λ€λ©΄ Taskμ μ§κΏμΈ Detached Taskλ 무μμΌκΉμ? π€ μΌλ°μ μΈ Taskλ μμ±λ μμΉμ μ°μ μμ, μ‘ν°, Task-Local λ³μ λ± λ€μν μμμ μμλ°μ μ€νλ©λλ€.
λ°λ©΄μ Detached Taskλ μ΄λ¬ν μμμ μ ν μμνμ§ μκ³ , μμ ν λ
립μ μΈ μ»¨ν
μ€νΈμμ μ€νλλ μμ
μ
λλ€. μ¦, λ°κΉ₯ μμ
κ³Όμ μ°κ²° μμ΄ μ€μ€λ‘ λ
립λ λΉλκΈ° μμ
μ μ€νν λ μ¬μ©λ©λλ€.
let task1 = Task(priority: .userInitiated) {
print("π Task1μ μμ
μ°μ μμ: \(Task.currentPriority)")
let task2 = Task.detached {
print("π Task2μ μμ
μ°μ μμ: \(Task.currentPriority)")
}
}
// Print "π Task1μ μμ
μ°μ μμ: TaskPriority.high"
// Print "π Task2μ μμ
μ°μ μμ: TaskPriority.medium"μ μμ μμ task1μ userInitiated μ°μ μμλ‘ μμ±λ μμ
μ
λλ€. κ·Έ λ΄λΆμμ μμ±λ task2λ Detached Taskμ΄κΈ° λλ¬Έμ, task1μ μμμ μμλ°μ§ μμ΅λλ€. λ°λΌμ task2μ μ°μ μμλ mediumμ΄ λ©λλ€.
κ·Έλ λ€λ©΄ Detached Taskλ μ΄λ»κ² νμ©ν μ μμκΉμ? WWDCμμλ μ΄λ―Έμ§ μΈλ€μΌμ λ€μ΄λ‘λνμ¬ μ»¬λ μ
λ·° μ
μ νμνκ³ , λμμ λμ€ν¬ μΊμμ μ μ₯νλ μμ
μ Detached Taskλ₯Ό νμ©νλ μμ λ₯Ό μκ°νμ΅λλ€.
@MainActor
extension MyDelegate: UICollectionViewDelegate {
public func collectionView(_ view: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt item: IndexPath) {
let ids = getThumbnailIDs(for: item)
thumbnailTasks[item] = Task {
defer { thumbnailTasks[item] = nil}
let thumbnails = await fetchThumbnails (for: ids)
Task.detached(priority: .background) {
self.writeToLocalCache(thumbnails)
}
display (thumbnails, in: cell)
}
}
public func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
thumbnailTasks[indexPath]?.cancel()
thumbnailTasks[indexPath] = nil
}
}μ μμ μμλ collectionView(_:willDisplay:) λ©μλ μμμ μ
μ΄ νλ©΄μ νμλκΈ° μ§μ μ μΈλ€μΌμ λΉλκΈ°λ‘ λΆλ¬μ΅λλ€.
μΈλ€μΌ λ‘λ© μμ
μ μΌλ°μ μΈ Taskλ‘ μ€νλλ©°, μ΄λ μ·¨μκ° κ°λ₯ν©λλ€. μΈλ€μΌμ΄ μ±κ³΅μ μΌλ‘ λ‘λ©λλ©΄, μ΄ μ΄λ―Έμ§λ₯Ό λμ€ν¬μ μ μ₯νλ μμ
μ Task.detachedλ‘ μ€νν©λλ€.
writeToLocalCache(_:)λ λμ€ν¬ I/Oμ κ°μ λ¬΄κ±°μ΄ λ°±κ·ΈλΌμ΄λ μμ
μ
λλ€. μ΄ μμ
μ UI 컨ν
μ€νΈλ μ°μ μμμ μν₯μ λ°μ§ μμλ λλ λ
립 μμ
μ΄λ―λ‘, Task.detached(priority: .background)λ‘ λΆλ¦¬νμ¬ μ²λ¦¬ν©λλ€.