streams_with_async.dart

import 'dart:async'; import 'dart:math' show Random; final random = Random(); // Mock data for a list of messages const messageList = [ { 'message': 'Message 1', 'timestamp': 1, 'uid': 1, }, { 'message': 'Message 2', 'timestamp': 2, 'uid': 2, }, { 'message': 'Message 3', 'timestamp': 3, 'uid': 2, }, ]; // Mock data for users const userList = { 1: 'User 1', 2: 'User 2', 3: 'User 3', }; // Data class for messages class Message { final String message; final int timestamp; final int uid; final String user; const Message(this.message, this.timestamp, this.uid, this.user); @override String toString() => '$user => $message'; } // Mimic a stream of a list of messages Stream<List<Map<String, dynamic>>> getMessagesMock() async* { yield messageList; while (true) { await Future.delayed(Duration(seconds: random.nextInt(3) + 1)); yield messageList; } } // Mimic asynchronously fetching a user Future<String> getUserMock(int uid) => userList.containsKey(uid) ? Future.delayed( Duration(milliseconds: 100 + random.nextInt(100)), () => userList[uid], ) : Future.value(null); // Transform the contents of a stream asynchronously Stream<List<Message>> getMessagesStream() => getMessagesMock() .asyncMap<List<Message>>((messageList) => Future.wait( messageList.map<Future<Message>>( (m) async => Message( m['message'], m['timestamp'], m['uid'], await getUserMock(m['uid']), ), ), )); void main() async { print('Streams with async transforms test'); await for (var messages in getMessagesStream()) { messages.forEach(print); } }
Example of how to transform streams of data in Dart/Flutter when the transform involves asynchronous calls.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.