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
430
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.1k
モバイルゲーム開発と Google App Engine
thara
0
350
GCPとAWSの比較
thara
0
120
Dart VM と Optional Typing
thara
0
360
Dart in なごやまつり
thara
0
54
Dartの基本
thara
0
62
Dart言語仕様 Pick-up
thara
0
540
Other Decks in Technology
See All in Technology
もう難しくない!誰でもカンタンDocker入門 〜30分であなたのPCにアプリを立ち上げる〜
devops_vtj
0
140
AIコーディングの最前線 〜活用のコツと課題〜
pharma_x_tech
4
2.8k
コードや知識を組み込む / Incorporating Codes and Knowledge
ks91
PRO
0
140
ガバクラのAWS長期継続割引 ~次の4/1に慌てないために~
hamijay_cloud
1
540
OpenLane-V2ベンチマークと代表的な手法
kzykmyzw
0
120
SDカードフォレンジック
su3158
1
660
更新系と状態
uhyo
8
2.1k
Microsoft の SSE の現在地
skmkzyk
0
240
ここはMCPの夜明けまえ
nwiizo
32
12k
「経験の点」の位置を意識したキャリア形成 / Career development with an awareness of the “point of experience” position
pauli
4
120
Рекомендации с нуля: как мы в Lamoda превратили главную страницу в ключевую точку входа для персонализированного шоппинга. Данил Комаров, Data Scientist, Lamoda Tech
lamodatech
0
840
グループ ポリシー再確認 (2)
murachiakira
0
180
Featured
See All Featured
Fontdeck: Realign not Redesign
paulrobertlloyd
84
5.5k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
47
2.7k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
30
2k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
119
51k
A Modern Web Designer's Workflow
chriscoyier
693
190k
Building a Scalable Design System with Sketch
lauravandoore
462
33k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
Writing Fast Ruby
sferik
628
61k
Mobile First: as difficult as doing things right
swwweet
223
9.6k
What’s in a name? Adding method to the madness
productmarketing
PRO
22
3.4k
Gamification - CAS2011
davidbonilla
81
5.2k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
19
1.2k
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."); });