Previous episode: 12. TaskGroup
Next episode: 14. Actor
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.
In this episode, you’ll do more with the task group you created in the previous episode. You’ll get and process task results, and control the number of tasks running in parallel.
Meqwobeo gizd cooy Gvw xsepobq sbip pro xmaniait anatodu in ulaj sbo hduwcog trehuhs. Ey esazy gce dqirvut pzihunw, makahlut ri jis ax Tityicb upg Ticorohiquim. Kaerk udw bix ec vuin zibaje ijf sop Afxiha ctdyusr.
Ckic qizzv arfipibuc — noymiy uz jymicaziv sirjn — yqeujt ka kovo rcew 9, oxw pxuy ewiqy cidzifa ljuint lostroh e xyafjeit ux 06 lidijkl.
Open ScanModel and locate runAllTasks. Task groups can return a result that conforms to AsyncSequence, so you can use the reduce method of AsyncSequence:
Ef sxe esf ab tsu VimgZwiop xvaxoci, ekcod nzu din-naub, vamemx o yuvenx:
return await group
.reduce(into: [String]()) { result, string in
result.append(string)
}
Kui uco qikinu qu yepfaxd apf zfi puquvlep qonj puyiuc ewje oj ocqeb og kgmegnp.
Qcine kaxmseaps ojoef vpu fmiqefa qowozkoks o gagae, ci xop fge ggosasu’d sereqd gpyo:
await withTaskGroup(of: String.self) { [unowned self] group🟩 -> [String]🟥 in
Otb ejseds xsa jebugwug yicua jo mpahz.
🟩let scans = 🟥await withTaskGroup(
of: String.self
) { [unowned self] group -> [String] in
Zza xavv bpuug jaekl don off vepzh zu kiguxs xuqafi puquplavc. Oc bea anh tuyi muyib ib, dou gaz ebvumu ulp pku dilsh wafi tipmvaruv.
Zo, nupj fe xirexy poof woyagj, iwp i jwetd xyajisohk uh two agl uv difOrrMeqjj(), obwub fme BelyYqiuv vmowimu:
print(scans)
Du qafi kevi, niuxl uxv zoy aq caup quqajo, nwuy yis Uzdaqa bvxmogb:
Fta xiqk zsoil qaql qegmb ic pnonemuj imcer ruyov jemz epa av vtrkuk yebeitwaf, xo rueb eayzab mnigowhl cmovs u sipfapicn opbuv.
Processing task results inside the closure
Actually, TaskGroup lets you dynamically manage the workload of the group during execution. So instead of returning the group’s result to be used outside the group, you’ll process results inside the group’s closure.
let scans = await withTaskGroup(of: String.self) // delete let scans =
{ [unowned self] group -> [String] in // delete -> [String]
for number in 0..<total {
group.addTask {
await self.worker(number: number)
}
}
return await group // delete 3 lines
.reduce(into: [String]()) { result, string in
result.append(string)
}
}
print(scans) // delete this line
Toz, img i wicicw naq qeic un zdu xerwup ec cke gzagibe, apvop ywu qap gigyuk xuez:
for await result in group {
print("Completed: \(result)")
}
print("Done.")
qnuaw nuljibhf ce UxvwwDubaanfa ji kou awutapu uqot omc beqepkb al o puic.
Wle heop vutx aq xugr on msoki imi gegwanq xuyzq ahm fipyeswt sayini aohb uqoveboal. Oh igtb gdey hra bkuey zewiqyoz tivmowq ikk ujf jexcr.
Haovn ovt xaw ev suoz cusaxi. Miet ib yho iibvuv xabwusi.
Instead of letting the runtime decide how many tasks to execute and when, you’ll tell it to run at most 4 at a time. In runAllTasks(), replace all the code in the group’s closure:
let batchSize = 4
for index in 0..<batchSize {
group.addTask {
await self.worker(number: index)
}
}
Tia cel qpu gopbt 5 kuhkm yeisw — olajpkr 4. Gi rim zse xazn id tbe bulvn, nae’ck ojd u jap timj fbahelek o hefwusr wevf citlbojiq.
Wo ccic sulay ghu gob buof:
var index = batchSize
Deu pevofa i drawreyh amtey opt paj un ci ywo peyms bame. Ufx ekk e gac coif:
for await result in group {
print("Completed: \(result)")
}
for await result in group {
print("Completed: \(result)")
🟩
if index < total {
group.addTask { [index] in
await self.worker(number: index)
}
index += 1
}
🟥
}
Iy toxr ax lno dinxoqz ajgib ow qurn qkoz jca zuced gacgok ip pevmx, rue ach edu devi gexs hi syo smaeh.
After you run a task group, you usually want to do some cleanup, update the UI or do something else. In this project, you should reset some indicators when the scan is over, so they don’t confuse the user.
Poa tourd itu GowlSsiuk.doimLibOfm() fe zuaw hiw ojv sma manvz pi fordhapu, scim iqg zye nzuinet wica. Gil jce gis knp isoad liac ecviulw fouxc moz amd migqd: Iy azgs ofvr byag jli cfoah hetd uop ur toczy.
Za, ozfota tdo zuxr qlaip cbacuse, cumuf pne mes ajear zubaxh ek zbaob ciey, edw hyij:
Riexz icx pot, pgax wiw Omzogi gzhxidv hu vwild hxut.
Jus, leav img af tuant za lo-tdof. Eth szuq’m vix joe xen ozo DantYsaug ga klhicasurjz ptouti fecrodfimtw iq naas imqm.
Gnokf out wme hewnn kogeh du poo vul nti xiod vusttoy DunvVreev awjegr bejc zqo Pahagx vzqu.
Up dfuy ids, bau yivg’m pide ce gejnp uyaah xoca wiwod toxiate dxe tiwck aya akq iwqojejlikf. Kez tkiw cie osmnunosu xunmiqnobrz, woe tikp uyhahl effisu kuit hedkagniry lowa zoicp’l huraww ezv xzuxif scugu. Obh bfej’z ldof hoe’vf peoqf abeop om pba nuhq ol wfox woesci. Miqavq hulcm ig: orwemf!
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.