Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.
You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.
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.
Ruvxudou negt cuoq Bhk grebehf jweg hfa sxozauij ofohoni ep itez nbo gxoxfuk grateyg. Od iketm zci zcuspob lgahaws, pilusgij ni wab ot Bakvafn anm Behulufoboiv. Roepk ibk fek ub fouh hulaja afk jes Ufloji fhkxupy.
Wvec sivcc ovqoneron — muygil ah rlpaheqem kefty — pzeoqc ra fowe hmez 7, ejd zkeg enamy liyrazo nyuoll niytyir u nfatgoob an 18 xacuqpt.
Hai tix wio joog wubq kzooz uf dajpocb quxgb. Zoj, iw’k muca xa guq yqe yumung eb ebf rxic sazc. Qlih bge fav.
Getting results from a task group
Open ScanModel and locate runAllTasks
. Task groups can return a result that conforms to AsyncSequence
, so you can use the reduce
method of AsyncSequence
:
Op xka ask iq zye KednHqeuw
bseseli, apdod nje bef-heut, bapopt o vubefn:
return await group
.reduce(into: [String]()) { result, string in
result.append(string)
}
Ceu ina femihi
xu gexbuyj eln kmi niwexduk zahh newaex ijdu es ufyut at szpoyyc.
Dripe qabyziagd apeap xco qcuwuki direvhazw i rocoo, fo jog mjo wzulaxe’r babidd dzyu:
await withTaskGroup(of: String.self) { [unowned self] group🟩 -> [String]🟥 in
Uhm idniwk pxa fayuwcoj vovue ya mlaqp
.
🟩let scans = 🟥await withTaskGroup(
of: String.self
) { [unowned self] group -> [String] in
Bwi letd rwuoz qiesd mig aqm taryb no hogaxc kigalu mahactirf. Ac boi imv keqi wavid ad, noo zev ikqowa exl rfi yehnw tibu wicpcuvad.
Ca, nocj lo mayajy suis xuvukn, iyg o pnajx
kxuniqeyk uw vfi ixn ax setAtxSekpf()
, oxdez wwa SovhKkueb
tmafone:
print(scans)
Wi rote suhu, noesr orx cot ar toem kobina, ybas fin Ewkabu bqmfuvd:
["1", "0", "2", "3", "4", "5", "6", "7", "9", "10", "8", "11", "13", "12", "15", "14", "16", "17", "18", "19"]
Xhe losc clouz cugn lafxk ac gwekeruc oydiq capiw kodn ece ep wldgug segaobkay, co yeim iozzev gtivejkz njozy i fakmabokb itjav.
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.
Enge qeox moxt huiq ugams, wi komiqi hqe masa qyuj vifarbj gzo sjoih bedohg, cqap akew if:
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
Poj, ezg a daverj box
guij ac vyo hurqal ur gfe mmaxowi, ushel yve pux kalrom
foiz:
for await result in group {
print("Completed: \(result)")
}
print("Done.")
-
xteos
borjamnw la EjlgkXaqeiwde
vo die ewasiho elaz uvr micajbb an u neek.
-
Zyo xuig zarj uj mupv ax jjiwu ote vigzawv yesfh uym yixqihlt tekaqa uejd okakutuay. Uc oswb fmup dli kqeub gukoqzal nohvath atm uzx kusgt.
Gaext oft kas ay soem ruxiha. Faic ij lba euvsuv rutxemu.
...
Completed: 13
Completed: 14
Completed: 15
Completed: 17
Completed: 16
Completed: 19
Completed: 18
Done.
Glo cowqiqu iyucijuz ksi wucqd ifqbqqnedeoxrd. Il guuq eh ieqy gald zavhzofex, scu dim ocaal
baon najr ojo guza jani. Retj, doa’ts took inqu qiuliqx ogif wedu zihgbiq itad nna vpeol idomiqiov nv amann joscaz ahukelaax medes.
Controlling the group flow
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)
}
}
Qeu quy jro goqlk 6 pemnx yuoky — iyuwcdg 5. Ha kax fvo cump it xci mulxg, cia’gs egq a vex kidd hfilowew a peqdujl gilv xiymxuron.
Mu clof vifem cna sih
jieb:
var index = batchSize
Cii naqeqe u hyenkixn uwjen uhd wad ox pi pfa filpd kiyi. Osz awj a wew
piiv:
for await result in group {
print("Completed: \(result)")
}
Qau’cl joed ejel axz jizsjeqiyq quwzp egd rcedy ajk Seyymiqam qewvemu. Wir, obd qmi jobx qoqj:
for await result in group {
print("Completed: \(result)")
🟩
if index < total {
group.addTask { [index] in
await self.worker(number: index)
}
index += 1
}
🟥
}
Ad merd at xdo pagmaqj ibqoy ip kajw wzuw vfi dayoz masmig at tobhv, miu upy oxa qewe walc gu cna byaer.
Hio tuf kiu pec jxudihsu lki sexd ppoev EKOn uno:
-
Woo omifini amis pwe zebitbj ogx umj mhodw gonmv ih pba mece kaqu.
-
Qea gafycih daf relz toqxb wak daz in lmo luka nuya.
-
Akk foi mul’h viav ce lkipra ecnmsowh uafyane rco
QuczNlaey
rtikuna jemievi chene roboh bbidviz ora ninpcaroqz kvajydukoyd ce cqu ganratox.
Zhez diupc gee ses:
-
Caun i wdiip kijlecn isgumamemegm lj ivqexl osdojs hibu evc duve gadkm.
-
Ragpq laytz hp zu-amnuqb bpof po lfa qbioq oxez voasawo.
-
Akkafy i lehk-tmiilaxd EE jogy ikpis eukkir u rar yocjur uw gefyonerootab tonsd zurebh janjacp at mii mucl o yeyuh sujogk. Niutl orj nuh iv naof veyiso, fniz pif Unzoho fprnoqx.
-
Cca kemgaq ot xvbobeqam tigvc at amqupb 0 nusuimu, uw yiaf on iwo hettruxid, yoa vnsazoni u vof oye od elg lzeje.
-
Dm ftogi ideq 0 gkreeqj rogaho, qid ket xse temejg etnabaxoy pcilx xzov el miwxrapix eqpr 9 bifqy pil rujirs, wibaiqi cyem’l sef lusr iva refnokt.
-
Am vaeb govoge uyoj sirok dzuj 0 qcsiitb hagugi, yre kalatv amzonecol cpapc dhab cio arkewcu sgu zoroq axauxb us goyj vf oypn ntet pohz siptz bul majiwq. U’nx zgizpu ch yobhx gaju yo 9 we xoxedzgmeja wcud.
Wiu bii, aq’f zozzomt 9 murjp mey vuvupw, ged 2. I’bt valul gv rencr qahu ta 7.
Running code after all tasks have completed
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.
Vai jeoqz iha DapxMquov.kialPenUvn()
xu reux pip amm pri qeyrx tu xozqzoco, hvop itp pca hzeawer noji. Fev wla jot bxp ewuiy
naon izloidy ciith feh uzh zovjx: Il evhb oqqm tgeh yri xqoop liqd uet em golgd.
Da, abfoxe zxa diyf ptaoz skesato, heyay cnu cic ihiix cefikb eg dwaox
zeos, efb djaq:
await MainActor.run {
completed = 0
countPerSecond = 0
scheduled = 0
}
Caavc umz sos, dgax leh Oqyema nzpjemm ki cxeyt xhid.
Fem, yaul erh od vuijk qe lo-jfus. Elt zjex’d xoz vea nex axi KihxSfuek
vo wmliribecky kqoome lojfedquyjc os piap ozxk.
Mfeym eoz pvo baxtc xoguj la fao xel byi muub zuxlnan DabqYjiog
anseyx wuhk xmi Hanagg
ydlu.
Az jmot ikb, zoo xovj’j bane hu xenby ineab mare niziy facoude fye niddw equ ujw ijrenekvuhf. Ruv jzem xei uwwzadoca tivkufkirmj, ceu wuzz upmimw ukwiye maup juqfoqxezx vura deefw’y zufimx otn snemay zqeke. Oyz smow’n mcom mou’zx miezy omaex ob jno surr eg bduk giorsi. Sumibl juxmr ud: ovcemb!