Skip to content

Instantly share code, notes, and snippets.

@mjohnsullivan
Created December 3, 2019 17:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mjohnsullivan/a1dcabc3c12921f303a4e62f149f5d04 to your computer and use it in GitHub Desktop.
Save mjohnsullivan/a1dcabc3c12921f303a4e62f149f5d04 to your computer and use it in GitHub Desktop.
Example of how to transform streams of data in Dart/Flutter when the transform involves asynchronous calls.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment