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
460
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.2k
モバイルゲーム開発と Google App Engine
thara
0
360
GCPとAWSの比較
thara
0
130
Dart VM と Optional Typing
thara
0
380
Dart in なごやまつり
thara
0
56
Dartの基本
thara
0
67
Dart言語仕様 Pick-up
thara
0
580
Other Decks in Technology
See All in Technology
AI人生苦節10年で会得したAIがやること_人間がやること.pdf
shibuiwilliam
1
270
クマ×共生 HACKATHON - 熊対策を『特別な行動」から「生活の一部」に -
pharaohkj
0
290
専門分化が進む分業下でもユーザーが本当に欲しかったものを追求するプロダクトマネジメント/Focus on real user needs despite deep specialization and division of labor
moriyuya
0
980
AWS re:Inforce 2025 re:Cap Update Pickup & AWS Control Tower の運用における考慮ポイント
htan
1
200
LLMでAI-OCR、実際どうなの? / llm_ai_ocr_layerx_bet_ai_day_lt
sbrf248
0
430
反脆弱性(アンチフラジャイル)とデータ基盤構築
cuebic9bic
2
160
20250807_Kiroと私の反省会
riz3f7
0
130
「育てる」サーバーレス 〜チーム開発研修で学んだ、小さく始めて大きく拡張するAWS設計〜
yu_kod
1
250
Tableau API連携の罠!?脱スプシを夢見たはずが、逆に依存を深めた話
cuebic9bic
3
210
Perlアプリケーションで トレースを実装するまでの 工夫と苦労話
masayoshi
1
410
AIエージェントを現場で使う / 2025.08.07 著者陣に聞く!現場で活用するためのAIエージェント実践入門(Findyランチセッション)
smiyawaki0820
6
550
Amazon Bedrock AgentCoreのフロントエンドを探す旅 (Next.js編)
kmiya84377
1
100
Featured
See All Featured
Agile that works and the tools we love
rasmusluckow
329
21k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
Faster Mobile Websites
deanohume
308
31k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
8
870
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
7
790
Java REST API Framework Comparison - PWX 2021
mraible
32
8.8k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
35
2.5k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.8k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
44
2.4k
Fireside Chat
paigeccino
38
3.6k
Visualization
eitanlees
146
16k
Art, The Web, and Tiny UX
lynnandtonic
301
21k
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."); });