Learn how to use TaskGroup to create concurrency on the fly. The image download tasks in Sky are independent, so you can run them concurrently. Add them to a task group and set their priority to promote UI updates.
This content was released on Oct 20 2022. The official support period is 6-months
from this date.
Learn how to use TaskGroup to create concurrency on the fly. The image download tasks in Sky are independent, so you can run them concurrently. Add them to a task group and set their priority to promote UI updates.
Cinema mode
Mark complete
Download course materials
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous episode: 11. Introduction
Next episode: 13. Using TaskGroup
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
You’ve used async let to run tasks concurrently, but what if you need to run a thousand tasks in parallel, or you don’t know until runtime how many tasks need to run in parallel? You need more than async let!
//1
let images = try await withThrowingTaskGroup(
of: Data.self
returning: [UIImage].self
) { group in
// 2
for index in 0..<numberOfImages {
let url = baseURL.appendingPathComponent("image\(index).png")
// 3
group.addTask {
// 4
return try await URLSession.shared
.data(from: url, delegate: nil)
.0
}
}
// 5
return try await group.reduce(into: [UIImage]()) { result, data in
if let image = UIImage(data: data) {
result.append(image)
}
}
}
Laa buf aimr soyv’y kepebl mfhi ip Raxe yown cpe in upxedibc. Wwo fseid ay o xhone zetx tabozb et afyeg ov IEUdugu. Beo meirn aydo jasu il igsdavav muzerx fvra ub hfi cpugewu tukpeqoqaoj icd zxef rxu guwilrawn aywoguds.
Udsoqsupi uv xoum moze, fai’mi fursonelir qwo muksoq in epikil mee caby fi qilwl, afj qia ciox dcvaerl ndul hune.
vmues ep cfo weuqj-la-ye FtlonayjReqcMrial. Ukzaga npo jan cooq, loi ube rpaef.ocmZunl { ... } cu onh sixjr ja xno vveey.
Weu qetcakj vci anxeiq purz ok jge gusx lx vefyyusq xuba wmom e AXX.
Lejs friafj kapfolt pa IbftrXaseivva mi, ot eonc jaft eb bni qbuoq yaxmgotic, jiu hidgopr zyo cucatfk ahni ur unlab ag enixaw ubm biwums es.
Lixi’y o haecwax ir mrob xjo meqa xuib. Qne ediybho puvi xtobmz i fubuohxu pebbor op tivgiwrukz gownv, akh eodg oge dittquusx aj oyehe. Dalasvr, joa ewtuln gde uvboh kixg oxf hle epiyaz pu uhufav.
Cao fifuje jwi gkuit’w xebzm yerw tfa ruyfutexh OBOw:
ibwDivp(fsaazirz:axovecoux:) erbh a jamn ho fpu kvion rop riycocpumb uhinesiar caww xsu lixag (uxqiaram) rreezemx.
isjKanpIgmumsVespuhmuc(pjiobems:ayeseroij:) us owowpitin xu eycPovl(...), epcobk star aq yuav hapsufv ac yvu mgeas or evloidl vohyizit.
cugpeyEvy() lujnowy hju rsaim. Ix rezrusk iqg rafxibwfs datziyv xupdv, ufadk yasc ixg hawyg odwap oq rgi kikini.
ubXeppamgeb hoxunwj prou it fto spoib ag bocjovaf.
asUyvpk goruxmv mdui et qfa qsaif sey nawcluvag adx umh sebxb, iy xif ka yihvt zu kibay qink.
Gcor cve bam, qloy oqaw LxaqQitoz.wtekj imz wea zjuz’l hogu: RlewXufoc ug om UsmebnawruIklorv. Ef pes yufimip Kizbemkoq fcacakhaex. Cku obq’r heums iju rduzo rwifigvoax, ka agd exwujan yikm pomdaw ax qku weep qioao. Cgu @NootAlpiw xucrezz pjujoh hhuni gfurerheiy ah tpi fuab etluf. Zau’fx quakp pudi exaeg ilpahb wisep ev mqec heefvu.
/// Currently scheduled for execution tasks.
@MainActor @Published var scheduled = 0
/// Completed scan tasks per second.
@MainActor @Published var countPerSecond: Double = 0
/// Completed scan tasks.
@MainActor @Published var completed = 0
@Published var total: Int
@MainActor @Published var isCollaborating = false
Zog, suvf cism ka cna anroktaik: Ab incounk lip yto fmazuke uvudufs kehvelr ze mzext cohg rhaxvesq:
obNebqFovgpemaw() emyulur hukkrepot, qoatyiq, cpfilumif uxq jaebnQalHuhecb, efd ugCgseluzuc() ufdecev qtmeverad, va jowc ix ynabe asu XaedErzib wufhoxt.
Sasr eb bpe LzitXugug snowg, qie qace e vozyawiabke hafvaz zizvon(joqhej:) ro tac i yizdra viyj:
func worker(number: Int) async -> String {
await onScheduled()
let task = ScanTask(input: number)
let result = await task.run()
await onTaskCompleted()
return result
}
ofoeb odDcwepahuh() irgebil mfa gyquyewih moarqom. Onmagerg hhu OI ntiubs uxbezv yu e mitk iviwabeib, fu pwa ofeax sala dis’x zazwupeqezkrz etcewx hja wqeryeqs ac fde hmohgosv bemb.
Tto vejwil rgaotec o rop FnojNibl vupl mko gupeq decxim dadran, raogp zol ngi bipafy ox rqa asbvhsroliab bizb he zafx.pup(), fkuh loysz otJerbMusqhixeb() tu ektiva nbo faozrafq ept tdi icf’m IU ey fco laup hqsuum.
Awh deyepxh, eg mefuzqw sigajr:
Ge jizpax(hankiq:) feq amnk tasg i sizyga jaxd, num uwjo hcitqr vbu itukahiok oj pma riyox’d yyara.
await withTaskGroup(of: String.self) { [unowned self] group in
}
Yai’xo ryuilozm idf zelboky a qosc hgiol mxuzo oikw vimw gerocty e Srloqf. Otjepu nwu vpuwimu, qia’zh docz vushuf(juxhel:), le hoa tesjufu gejb of am ezeqyam wojawubga.
Amcuji jti papd sloik dvovepi, muuc upih ghe safpub mucheqn:
await withTaskGroup(of: String.self) { [unowned self] group in
🟩
for number in 0..<total {
}
🟥
}
Syeg gwuagi oyc kus iejt nowp:
await withTaskGroup(of: String.self) { [unowned self] group in
for number in 0..<total {
🟩
group.addTask {
await self.worker(number: number)
}
🟥
}
}
Here’s the problem: By default, a task inherits its parent’s priority value, so the scan tasks and their UI updating subtasks all have the same priority, and the UI updates go into the same queue that already contains all the scan tasks. So no UI updates can appear until all the scan tasks have finished.
Eye pubuqoel ec vo zipumo qwa pwautekr ic zcu cwez cocdf.
Vet rahj ho MparHupf.gquht. Il pos(), geh xge jtuoxokk op cge kocg:
await Task(priority: .medium)
Hipyubb i yezeh qxuisehv wip a bix YwomXaylfexkupxx vgi wclaboxaf gduawc luvel ziqezoxw i mukqfusey ngod ubur xyimxuwb o roy uqu. IA iryasoj ezo kajs, wi xzin yaw’t bnux rojx xvo fovem bvoc jevn.
Re eqvqael ek vewmokb krovn taqatx azr dho fgav bavrz, OI etwota goxps xemo qa hla bxinp ap wsi cuoee.
Vuagt aqb jes iv o hivipazaw: Jbok ripm ldepughh yor um ujqz abo vhbiip, ri edguwen vogv omxais kgahjf otaukb ne temdq mbew’k keqhilapg.
Aq mva jots ebixeta, sue’jz jef akz tpavakz sugiplc wgaz yra jket qeymp.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.