Skip to content

Instantly share code, notes, and snippets.

@fvisticot
Created March 19, 2019 17:35
Show Gist options
  • Save fvisticot/8cd79a9d5a2bea23fb1d1cba3b34ee2a to your computer and use it in GitHub Desktop.
Save fvisticot/8cd79a9d5a2bea23fb1d1cba3b34ee2a to your computer and use it in GitHub Desktop.
Dart async
import 'dart:async';
import 'dart:math';
//https://www.dartlang.org/articles/language/beyond-async
void main() async {
//final stocksSync = StocksService().stocksSync();
//print(stocksSync);
//final stocksAsync = await StocksService().stocksAsync();
//print(stocksAsync);
//StocksService().stocksAsync().then((stocks) => print(stocks));
//StocksService().stockStream('orange').listen((stock) => print(stock));
//StocksService().stockStream('orange').where((stock) => stock.price > 3.0).listen((stock) => print(stock));
Stream<String> descStream=StocksService().stockStream('orange').map((stock) => 'Mapped Desc: ${stock.name} is currently ${stock.price}');
descStream.listen((desc) => print(desc));
}
class StocksService {
final List<Stock> _stocks = [Stock(name: 'orange', price: 12), Stock(name: 'google', price: 9.0)];
List<Stock> stocksSync() {
return _stocks;
}
Future<List<Stock>> stocksAsync() async {
await Future.delayed(Duration(seconds: 5));
return _stocks;
}
Stream<Stock> stockStream(String name) async*{
for (int i = 0; i < 100; i++) {
await Future.delayed(Duration(seconds: 5));
yield Stock(name: name, price: Random().nextDouble()*10);
}
}
}
class Stock {
final String name;
final double price;
Stock({this.name, this.price});
factory Stock.fromMap(Map<String, dynamic> map) {
return Stock(name: map['name'], price: map['price']);
}
@override
String toString() {
return '$name, $price';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment