Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Future & Stream in Dart
Search
Tomochika Hara
July 27, 2013
Technology
0
470
Future & Stream in Dart
2013 Future & Stream in Dart
Tomochika Hara
July 27, 2013
Tweet
Share
More Decks by Tomochika Hara
See All by Tomochika Hara
Swiftでつくるファミコンエミュレータのススメ
thara
3
2.3k
モバイルゲーム開発と Google App Engine
thara
0
370
GCPとAWSの比較
thara
0
130
Dart VM と Optional Typing
thara
0
390
Dart in なごやまつり
thara
0
57
Dartの基本
thara
0
71
Dart言語仕様 Pick-up
thara
0
590
Other Decks in Technology
See All in Technology
AI時代におけるドメイン駆動設計 入門 / Introduction to Domain-Driven Design in the AI Era
fendo181
0
660
Datadog On-Call と Cloud SIEM で作る SOC 基盤
kuriyosh
0
160
CDKの魔法を少し解いてみる ― synth・build・diffで覗くIaCの裏側 ―
takahumi27
1
110
LINE公式アカウントの技術スタックと開発の裏側
lycorptech_jp
PRO
0
340
メタプログラミングRuby問題集の活用
willnet
2
760
Black Hat USA 2025 Recap ~ クラウドセキュリティ編 ~
kyohmizu
0
510
ソフトウェアエンジニアとデータエンジニアの違い・キャリアチェンジ
mtpooh
1
740
こんな時代だからこそ! 想定しておきたいアクセスキー漏洩後のムーブ
takuyay0ne
4
530
us-east-1 の障害が 起きると なぜ ソワソワするのか
miu_crescent
PRO
2
770
お試しで oxlint を導入してみる #vuefes_aftertalk
bengo4com
2
1.4k
これからアウトプットする人たちへ - アウトプットを支える技術 / that support output
soudai
PRO
16
5.1k
内部品質・フロー効率・コミュニケーションコストを悪化させ現場を苦しめかねない16の組織設計アンチパターン[超簡易版] / 16 Organization Design Anti-Patterns for Software Development
mtx2s
2
190
Featured
See All Featured
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
10
660
Optimizing for Happiness
mojombo
379
70k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
192
56k
Statistics for Hackers
jakevdp
799
220k
Reflections from 52 weeks, 52 projects
jeffersonlam
355
21k
Typedesign – Prime Four
hannesfritz
42
2.9k
How to train your dragon (web standard)
notwaldorf
97
6.4k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.3k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
51k
A Modern Web Designer's Workflow
chriscoyier
697
190k
GraphQLとの向き合い方2022年版
quramy
49
14k
Transcript
Future & Stream in Dart tomochikahara @zetta1985
Agenda • Future API • Stream API
Future API for Ansynchronous Programming
What is a Future? • 「先物」 ◦ 別名Promise。 ◦ 処理結果を必要となる時点まで保持する
◦ 並列処理のデザインパターン ▪ Dartでは非同期なだけで並列処理は必須でない • Futureの値を決めるCompleter ◦ Futureはあくまでも値を保持するのみ ◦ 計算結果をFutureに与えるのがCompleter • dart:io, indexed_dbなどで利用
Future & Completer Completer Future Future Caller Callee Future<String> echoToMountain(String
yo_ho); call echoToMountain create get Future return Future then((reply) => catchMyEar(reply)) complete(reply) Execution
Future & Completer import "dart:async"; Future<String> echoToMountain(String yo_ho) { var
completer = new Completer<String>(); new Timer(new Duration(milliseconds: 5000), () { completer.complete(yo_ho); }); return completer.future; } void main() { print("before echoToMountain"); var future = echoToMountain("YooooHooooo"); future.then(print); print("after echoToMountain"); }
Future Example new File("./foo.txt").fullPath() .then((fullpath) { print("foo.txt's fullpath is $fullpath");
}) .catchError((e) { print("foo.txt is not exists."); }); File IO (Async try-catch) HTTP Request (Async Process Chain) var uri = Uri.parse("http://tomochikahara.com"); new HttpClient().getUrl(uri) .then((HttpClientRequest req){ // prepare request req.headers.add("contentType", "text/html"); return req.close(); }).then((HttpClientResponse res) { res.transform(new StringDecoder()).forEach(print); });
Stream API for sequence of any data
What is a Stream? • イベントの「流れ」 ◦ 単なる遅延リスト。 ◦ 何回も使えるFuture。
◦ 値が発すること=イベント、と表現 ◦ Producer - Consumer Pattern ▪ Dartでは非同期なだけで並列処理は必須でない • DOM EventやByte IO、標準入力などで利用
Stream What is a Stream? Controller (Sink) Subscription D C
B' A' ・・・ Transformer F E add listen
Stream var controller = new StreamController<String>(); controller.add("A"); var stream =
controller.stream; stream.listen((str) => print(str), onError : (e) => print("Error"), onDone : () => print("Done")); controller.add("B"); controller.add("C"); controller.addError(new StateError("Illegal State")); controller.add("D"); controller.close();
Stream Subscription var controller = new StreamController<String>(); controller.add("A"); var stream
= controller.stream; var subscription = stream.listen((str) => print(str), onDone : () => print("Done")); subscription.onError((e) { subscription.cancel(); }); controller.add("B"); controller.add("C"); controller.addError(new StateError("Illegal State")); controller.add("D"); controller.close();
Stream Transformer var controller = new StreamController<int>(); var stream =
controller.stream; var transformer = new StreamTransformer<int, String>( handleData : (int value, EventSink<String> sink) { sink.add("$value:(1)"); sink.add("$value:(2)"); }, handleDone : (EventSink<String> sink) { sink.add("Done!"); } ); stream.transform(transformer).forEach(print); for (var i = 0; i < 10; i++) { controller.add(i); } controller.close();
Stream Example query("input#hello").onClick.listen((MouseEvent e) { window.alert("hello, world."); }); DOM Event
File Access StreamSubscription<List<int>> subscription; subscription = new File('bar.txt').openRead().listen((bytes) { for (var b in bytes) { print(new String.fromCharCode(b)); if (b == '#'.codeUnitAt(0)) { subscription.cancel(); return; } } });
Stream Example 標準入力 HTTP Server HttpServer.bind("127.0.0.1", 8080).then((HttpServer server) { server.listen((HttpRequest
req) { req.response.write("This message from my server."); req.response.close(); }); }); print("Please Input A."); var stream = stdin .transform(new StringDecoder()) .transform(new LineTransformer()); stream.listen((str){ print("Your input's length : ${str.length}"); print(str == "A" ? "Just A." : "Not A."); });