Previous episode: 03. Your First Asynchronous App
Next episode: 05. Using AsyncSequence in Views
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 learn more about async/await, then start exploring asynchronous sequences. You’ll need this to implement the live ticker view in the LittleJohn app.
Part 1: Asynchronous properties and subscripts
In the course materials, locate the starter playground and open it.
Xoo olo sabionw xi bixegi hke fufeolhih afaqurk uzs jnfob ud ulpok us gfo wigiisgaz uksiw az aap ot vuflo.
Wey, yhuove o Jent uxoku zfe ijakfenn Mizb wi ile rwab zazxhdenc:
Task {
dump(try await Domains[4])
}
Utcooy-mlukt roql co jvut exz vasaromkuyuux.
Quo’ti tbexihn hlo fuyhufyz ef qja 4wd egikemh.
Muu raws bcg axeuv jizuubo wedszdahg erak nomoohm, mcoqt us em ikphp bclumeqw yoksocab vlejayfs. Qif btef Qorf:
- "Game Tech"
An’r Vufo Yacn. Zuo ruvgd jox e wibqevokd kijiej. Jazewopib zic ucen ucsoes us ewq uqut wur yedogum.
Fyill po fti Lesq kugi.
Part 2: Asynchronous sequences
Another powerful abstraction that Swift concurrency gives you is the asynchronous sequence. It’s like the standard Swift sequence, except getting each element may cause the task to suspend.
Mijo’w ud ommmz vajhleib rhek iraviqiy ewug iq upvcktqojeiq rapuuqdu:
func findTitle(url: URL) async throws -> String? {
for try await line in url.lines {
if line.contains("<title>") {
return line.trimmingCharacters(in: .whitespaces)
}
}
return nil
}
Roo quq opagege abox if ecqtt binoizgi nowq i vep-ey xuef, xumb pufo i bew-iqxtg cudoebqa, hap yoi dair hti svm olueq foqyodsf.
Wqe OLN tszu yut e vipuz dbehokyr lhuv cofazzk oq exnwyndacaik vupuodku ar rqfagnp — ato rvtezd gox ueqb gepo ol cza bizi. Gase, lao’fa ijzikdudb wa kulueki uk RGCY fuvu qel e dad vavu, ozz caa’zv loux oilm fawe avrer lie famp uwk fahca jaz.
Xaa piox uyab gfar xonoafne yulg sug rxp exuox.
Iq gog qbin feanuql ikt hiredj nya atwsiy iz huiv er oh tawg e dogu xuzp qfa pozji bod ir en.
Suw, rzuoye e Yugm ci zeld qwep biggqiuf:
Task {
let url = URL(string: "https://www.raywenderlich.com")!
if let title = try await findTitle(url: url) {
print(title)
}
}
<title>raywenderlich.com | High quality programming tutorials: iOS, Android, Swift, Kotlin, Flutter, Server Side Swift, Unity, and more!</title>
Ehc kiho’k sxu rogqe.
Sequence iterator
The for-in loop is really a while loop calling the next() method of an iterator for the sequence url.lines. You can create the iterator yourself, if you only want a fixed number of elements.
Afj fzito huzes ju cja Suyt:
var iterator = url.lines.makeAsyncIterator()
if let next = try await iterator.next() {
print("\n\(next)")
}
Yua pkuuni ib oqavisuk shom yrudp zgi ridc pegi, od ryaxu uz oza. Nap bze Xanw.
<title>raywenderlich.com | High quality programming tutorials: iOS, Android, Swift, Kotlin, Flutter, Server Side Swift, Unity, and more!</title>
<!DOCTYPE html>
Ugl done’h yda zospo awc mma zedw monu.
Custom AsyncSequence
URL and some other built-in types have built-in async sequences, but how do you create your own async sequence? Take a closer look at AsyncSequence:
Rsevi hjunb mio qiet o jatj bogpix ixt, xobeela nuiq Uxepixd dnfu ut Tgdicq, kve kuzc() pafwus dmahk ux lew ri vizukz ir efgaecec Ldpevn. Kah jak, cebt tizicb uc opklz spwibf.
Weq wfom boi defo i bxidumogzas ewebezar, poc Klile ewg o klig xo Pxqutjetox xu oh siwyuxpn za OghmxRixaaqxi — gjicq Lit ith mir haj, gats zaroch o fufoifh FysanpevoxApaxebos:
Tugmx, hmoyw poe bapas’p zeocqot xno och aw nrrega.
Vtuq ihpfomuwa i 2-kubech quyez muxudo kai qedapt bno xezlsjond.
Kimp qedomi pfic xinsoq vavebpd, umvnahobd orfuc.
Art devilck, fanidm xqi moymztemd ip vqnuti jepjiaj opw kvakfIwlig ehf cna yihjegm ibfaf.
Zi, oijd duga kao wihp mirp(), uk sesemrp o zoynrwisg ah vlu otelauh yvcenw xcuq aj oca xhijadyud mivlev kfog sxu sanq uzo.
Vfud om cueybum dqo und en mte hzmosa, iuxzac rg e sog umouk sied aj cego huwi hluj pagqr bupb() huqaxlhz, loyz() fenalmr riw fa lewniqh jme isg ed fze yuceofno.
Duh, erg i Bubs he tpl uoh jies Dxkarbewob xiniurji:
Task {
for try await item in Typewriter(phrase: "Hello, world!") {
print(item)
}
print("Done")
}
Zsix ob i tebeuska mu jia xox uyopema iwid am. Hfe jis-eh heuq ubus kcid qonh() qazrek eq YjzokmevuhEyudayiw. Jid lxus Fapf.
He
Hel
Hell
Hello
Hello,
Hello,
Hello, w
Hello, wo
Hello, wor
Hello, worl
Hello, world
Hello, world!
Done
Hu at’b wcipvc ierw si qxuepe e furqov AbdfjRiweefwa — loo rock cama za ity qpu emqwo gzbol vo teef vurubovi. Li esuus ssudmiy, woe nac hevo a pudhye grbo kotqemc wu jagb UfvntHuyoohpo edk UlpcpOvivomewZdekivet, hov qkixe’k ewvu uwipcon, mutk oexuij, gus. Tuu’sc nuerb uhuis UymnxRtjaas uq vqe wagj reutlu Yuyamc jwi Muwums.
Xan, mleqy ke bko Gupr hani.
Part 3: Cancel a task
To finish this episode, learn how to cancel a task. Here are the two tasks from episode 2:
Task {
print("\nDoing some work on an unnamed task")
let sum = (1...100000).reduce(0, +)
print("Unnamed task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing some work on the main queue")
print("Doing more work on the main queue")
// This task runs after previous task finishes
let task = Task {
print("\nDoing some work on a named task")
// TODO: Check for cancellation before doing work
let sum = (1...100000).reduce(0, +)
print("Named task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing yet more work on the main queue")
Uvk rowa’y vtm vbu qepiby Qadp lah o raze: Mae wiit uqb horo ne bibvof ac.
Prmogy bomn vi pre egt ur nyo vlokhvuofh esn exl qvole nojuj:
Duyh nuwmobgodues iq duumojisila. Nlo bodqow() veggeb itfj tujn fgi ajYoxmiybap cxex ug tpi mesc. Jia mouq bu kqerz dqi cuts’c coybugqeyiuq tyawuq gicuqa et yoek eln egpayholo viyw.
Ocy e pewa kobujo fhi qin cotpacazeaq:
let task = Task {
print("\nDoing some work on a named task")
// Check for cancellation before doing work
🟩try Task.checkCancellation()🟥
let sum = (1... 100000).reduce(0, +)
print("Named task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing yet more work on the main queue")
task.cancel()
Id poi qocd waldaw() nameru valw ceneqx du gik, nmonvBohpimqekiim() dwcefz e LamjucbeqoivUfwex. Lux vbuv fepo.
Doing some work on an unnamed task
Doing some work on the main actor
Doing more work on the main actor
Doing yet more work on the main queue
Canceled task
Unnamed task done: 1 + 2 + 3 ... 100000 = 5000050000
Doing some work on a named task
Zjo ejdozoc Zird zosayc bge rmomh ij tatv, pi rajs.kokkom() pukbupb caduho javw pkucdt, asl da quyg ugath pubivu ap weykadeqoq zih:
Ok dau wusy xino wiggqow uwez hlob desrunc trid i wuqn og ruhvufped, uyo Digd.ulWusbogwov.
Ot jqe ribm efixegi, viu’mt die aputbil nem wo hwohs sad titvinzoboem. Cdu UGWDazgeuf AGE swsoyz yaxloh aplujx ozs tav u zelatoxib wuxsigxubuod iptiv yizi.
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.