Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Meet AsyncSequence

Meet AsyncSequence

AsyncSequenceってなに?

Mobile Act ONLINE #5 で AsyncSequence の話をしました #MobileAct - usami-kの日記
https://usami-k.hatenablog.com/entry/2021/07/01/083448

Mobile Act ONLINE #5 〜 WWDC21 を振り返る 〜 - connpass
https://mobileact.connpass.com/event/216108/

0b26590a0a8b0f1da140ed5de9b68379?s=128

USAMI Kosuke

June 30, 2021
Tweet

Transcript

  1. "TZOD4FRVFODF ͬͯͳʹʁ Ӊࠤݟެี  1/16

  2. Ӊࠤݟެีʢ!VTBNJLʣ w 鳍鲟鳫鳢鳣גࣜձࣾJ04鲠鳫鲰鳃鲚鲾鲻鲧鳢鱅鳁 w ٕज़ಉਓࢽ w $PNCJOF鲗鱴鱝鲆鲍鱋 w $PNCJOF鱭6*,JU鱰鲍鲐J04鲚鳏鳢։ൃ w

    هࣄࣥච༧ఆ w J04%$+BQBO$PNCJOF0QFSBUPS鲤鲜鳁 2/16
  3. 4XJGU$PODVSSFODZ w ඇಉظॲཧ鱑࣮૷鱜鲉鱞鱔鱯鲐ʢJ04Ҏ߱ʣ w asyncawait w 4USVDUVSFE$PODVSSFODZ w "DUPS w

    ࠓճ鱴asyncawait鱳࿩ 3/16
  4. BTZODBXBJUΛ࢖Θͳ͍৔߹ func fetchThumbnail(completion: (UIImage?, Error?) -> Void) { let task

    = URLSession.shared.dataTask(with: request) { ... if let error = error { completion(nil, error) } else { // ... data / response ͷॲཧ ... completion(thumbnail, nil) } } task.resume() } 4/16
  5. BTZODBXBJUΛ࢖͏৔߹ func fetchThumbnail() async throws -> UIImage { let (data,

    response) = try await URLSession.shared.data(for: request) // ... data / response ͷॲཧ ... return thumbnail } w await鱳Օॴ鱬鲭鲱鳒鳫鳁ɺॲཧ鱑ऴ鲔鱨鱤鲎෮ؼ 5/16
  6. 63-4FTTJPOͷϝιου // async / await ඇରԠ൛ func dataTask(with request: URLRequest,

    completionHandler: (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask // async / await ରԠ൛ func data(for request: URLRequest) async throws -> (Data, URLResponse) 6/16
  7. "TZOD4FRVFODFͱ͸ w Sequence鱳asyncawaitରԠ൛ w 鱮鱋鱉鱋鱘鱭ʁ w 鲃鱟Sequence鱳鱏鱚鲎鱉 7/16

  8. 4FRVFODF w Sequence鳏鳥鳀鲫鳣鱰४ڌ鱜鱤ܕ鱬鱴ɾɾɾ w for-inߏจ鱑࢖鱍鲐 w ஋鱴ಉظత鱰౉鱚鲑鲐 for quake in

    quakes { // ... quake ͷॲཧ ... } 8/16
  9. "TZOD4FRVFODF w AsyncSequence鳏鳥鳀鲫鳣鱰४ڌ鱜鱤ܕ鱬鱴ɾɾɾ w for-await-inߏจ鱑࢖鱍鲐 w ஋鱴ඇಉظత鱰౉鱚鲑鲐 for await quake

    in quakes { // ... quake ͷॲཧ ... } 9/16
  10. 4FRVFODFΛΠςϨʔλͰݟΔ for quake in quakes { // ... quake ͷॲཧ

    ... } var iterator = quakes.makeIterator() while let quake = iterator.next() { // ... quake ͷॲཧ ... } 10/16
  11. "TZOD4FRVFODFΛΠςϨʔλͰݟΔ for await quake in quakes { // ... quake

    ͷॲཧ ... } var iterator = quakes.makeAsyncIterator() while let quake = await iterator.next() { // ... quake ͷॲཧ ... } 11/16
  12. "TZOD4FRVFODFΦϖϨʔλ let strings = quakes.map { (quake) -> String in

    // ... quake Λ String ʹม׵ ... } for await string in strings { // ... string ͷॲཧ ... } 12/16
  13. "TZOD4FRVFODFͷฒྻॲཧ let task1 = async { for await quake in

    quakes { // ... quake ͷॲཧ ... } } let task2 = async { for await string in strings { // ... string ͷॲཧ ... } } // task1.cancel() 13/16
  14. $PNCJOFͱͷൺֱ w AsyncSequence鱴$PNCJOF鱭ѻ鱋໰୊ྖҬ鱑ࣅ鱫鱉鲐 w AsyncSequence w J04Ҏ߱ɺݴޠ૊鲄ࠐ鲄ߏจɺ鲯鳫鳏鳣鱬෼鱐鲏鲉鱞鱉 w $PNCJOF w

    J04Ҏ߱ɺ鲢鳒鳤鱅鲷鱑๛෋ɺෳ਺鲱鳀鳢鱅鳘鱳鳖鱅鲰 14/16
  15. ࠓޙ͸Ͳ͏ͳΔʁ w ڞଘʁ w $鱬鱴asyncawait鱭3Y鱑ࠞࡏ鱜鱫࢖鲔鲑鱫鱉鲐 w ༥߹ʁ w ࢓༷ࡦఆத鱳AsyncStream鱑鱏ޓ鱉鲗༥߹鱞鲐鱐鲇ʁ w

    ݱ࣌఺鱬鱴鱮鱦鲎鱭鲇鱉鱍鱯鱉 15/16
  16. ࢀߟ৘ใ w 88%$鲳鲻鲯鳟鳫.FFU"TZOD4FRVFODF w "1*鳢鳍鲙鳤鳫鲱AsyncSequence鳏鳥鳀鲫鳣 16/16