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

Dart's Async Stream<T> gotchas

Dart's Async Stream<T> gotchas

About Dart's async Stream and syntax sugers, async*, await for...

5d429874243e641a1684a364211ddc16?s=128

UEHARA Junji

March 29, 2018
Tweet

Transcript

  1. Dartの非同期ストリーム 周りをちょっと見てみる NTTςΫϊΫϩεגࣜձࣾ ্ݪ५ೋ Dart Meetup Tokyo #4 2018/3/29

  2. ࣗݾ঺հ ্ݪ५ೋ(@uehaj) ॴଐ: NTTςΫϊΫϩεגࣜձࣾ ޷͖ͳݴޠ(౳) Groovy,Elm,Rust,Haskell,JavaScript(React/Redux/ Redux-Saga,Cordova, ReactNative), Dart [new!]

    ॻ੶ ϓϩάϥϛϯάGroovy(ٕධ) Grailsపఈೖ໳(ᠳӭࣾ)
  3. ͸͡Ίʹ Dartݴޠɺྑ͍Ͱ͢Ͷ! 2013೥ʹࢼͯ͠Ҏདྷ5೥ͿΓ2౓໨ ྑ͍ͱࢥͬͨ͜ͱ ฏ໌ɺৗࣝతɺྑ͍ͱ͜ͲΓ ଞݴޠͷܦݧ͔Βྨਪ͕ޮ͖ͦ͏ Ͱ΋ݟͳΕ͵΋ͷ΋͋Δ async*, await for

  4. ࿩͢͜ͱ Dartͷؔ਺ఆٛͷम০ࢠ(async, async*, sync*)
 ͬͯԿ? ಛʹasync* Ͳ͏࢖͍Θ͚Δͷ? await for Stream<T>

  5. ؔ਺म০ࢠ ྫ ໊শ ΧδϡΞϧͳઆ໌ म০ͳ͠ T 
 func() {} ؔ਺

    ී௨ͷؔ਺ async Future<T> func() async {} ඇಉظؔ਺ BTZODGVODUJPOT +4$ͷBTZODؔ਺ sync* Iteratable<T> func() sync* {} ಉظδΣωϨʔλ (synchronous generators) JS/PythonͷδΣωϨʔλ async* Stream<T> func() async*{} ඇಉظδΣωϨʔλ
 (asynchronous generators) ???
  6. Stream<T> is Կ? ୯Ұ஋ ෳ਺஋ ಉظ T Iterable<T> ඇಉظ Future<T>

    Stream<T> • ͜͜Ͱͷ”ඇಉظ”͸ʮݱεϨου಺Ͱ͸஋͕औΕͳ͍ʯఔ౓ͷҙ • Streamʹ͸ෳ਺ϦεφΛొ࿥Ͱ͖ΔϒϩʔυΩϟετετϦʔϜ ͱɺҰ͔ͭ͠ొ࿥Ͱ͖ͳ͍୯Ұొ࿥ετϦʔϜ͕͋Δ͕(ܕ͸ಉ ͡)ɺasync*͸୯Ұొ࿥ετϦʔϜΛฦ͢ɻ
  7. StreamͱIterableͷҧ͍

  8. म০ͷޮՌ ྫ ؔ਺಺Ͱ࢖͑Δ return await await for yield yield* म০ͳ͠

    T func() {} ✔ × × × × async Future<T> func() async {} ✔ ✔ ✔ × × sync* Iteratable<T> func() sync* {} × × × ✔ ✔ async* Stream<T> func() async*{} × ✔ ✔ ✔ ✔
  9. async*ؔ਺म০ࢠͱ͸ தͰawait(for)͕࢖͑Δ ඇಉظॲཧΛಉظॲཧͷΑ͏ʹॻ͚Δ தͰyield͕࢖͑Δ Stream<T>Λฦ͢δΣωϨʔλ(త)ؔ਺ StreamContorllerΛ࢖ͬͨStreamੜ੒ίʔυͷγϯ λοΫεγϡΨʔ

  10. async*Λ࢖͏ͱ͖ yieldͰStream<T>Λ৽نʹɺ΋͘͠͸ผͷStreamΛՃ ޻ͯ͠࡞Δ ผͷStream<T>Λyield*Ͱ݁߹͢Δ ετϦʔϜॲཧΛݟ΍͘͢ॻ͖͍ͨ c.f. RxDart, flutter.async.*

  11. await forͬͯԿ? ετϦʔϜʹର͢ΔҎԼͷॲཧΛforϧʔϓΆ͘ॻ͘γϯλοΫεγϡ Ψʔ A. ཁૉ਺ճ࣮ߦ͞ΕΔΠϕϯτϋϯυϥઃఆ B. (Ωϟϯηϧ࣌Τϥʔϋϯυϥઃఆ) C. Ұ࿈ͷΠϕϯτϋϯυϥ࣮ߦ͕׬ྃͨ͠ͱ͖ͷඇಉظίʔϧόο

    Ϋઃఆ D. Cʹ͍ͭͯawait ඍົɾෆศ ແݶ௕ετϦʔϜʹద༻͢ΔͱɺC΍Dʹ౸ୡ͠ͳ͍ CͰͷFutureͰൃੜ͢Δඇಉظྫ֎ΛߏจతʹΩϟονͰ͖ͳ͍
  12. await for͸γϯλοΫεγϡΨʔ try { await for (elem in stream) {

    AAA } } catch (e) { BBB } CCC stream.listen((elem) { AAA }, onError: (e) { BBB }, onDone: () { CCC } );
  13. await for͸ॊೈੑ͕௿͍ listen()ͳΒ ແݶ௕ετϦʔϜΛѻ͑Δ listen()͕ฦ͢StreamSubscriptionΛasFeature()Ͱ FutureԽͯ͠onErrorΛϋϯυϧͰ͖Δɻ

  14. Stream<T>͸Dartඪ४ϥΠϒϥϦͷͲ ͜Ͱ࢖ΘΕ͍ͯΔ͔ DOMΠϕϯτɺWebSocketΫϥΠΞϯτ (dart:html) ϑΝΠϧIOɺHTTP/WebSocketαʔό(dart:io) ΞΠιϨʔτؒ௨৴ʹ࢖͏ReceivePort

  15. Stream<T>͸Flutter SDKͷͲ͜Ͱ࢖Θ Ε͍ͯΔ͔ StreamBuilder: Stream͔ΒWidgetΛੜ੒ EventChannel.StreamHandler: ωΠςΟϒϞ δϡʔϧ͔ΒDart΁ͷσʔλड৴ flutter.async.*Stream* GUIΠϕϯτॲཧ͸StreamͰ͸ͳ͍

    [※] https://medium.com/@svenasse/flutter-event-channels-89623ce6c017
  16. ·ͱΊ async*͸ɺStreamΛδΣωϨʔλͷΑ͏ʹॻͨ͘Ί ͷγϯλοΫεγϡΨʔͰͨ͠ Stream<T>Λཧղ͢Δඞཁ͕͋Δ ←ॏཁ

  17. ࢀߟࢿྉ Dart Language Asynchrony Support: Phase 2 https://www.dartlang.org/articles/language/beyond- async ϓϩάϥϛϯάݴޠDartͷجૅ

    https://www.cresc.co.jp/tech/java/Google_Dart/ DartLanguageGuide.pdf