getUnreadChatsCountStream method
Retrieves a stream of the count of unread chats.
Implementation
@override
Stream<int> getUnreadChatsCountStream() {
// open a stream to the user's chats collection and listen to changes in
// this collection we will also add the amount of read chats
StreamSubscription? unreadChatSubscription;
// ignore: close_sinks
late StreamController<int> controller;
controller = StreamController(
onListen: () async {
var currentUser = await _userService.getCurrentUser();
var userSnapshot = _db
.collection(_options.usersCollectionName)
.doc(currentUser?.id)
.collection(_options.userChatsCollectionName)
.snapshots();
unreadChatSubscription = userSnapshot.listen((event) {
// every chat has a field called amount_unread_messages, combine all
// of these fields to get the total amount of unread messages
var unreadChats = event.docs
.map((chat) => chat.data()['amount_unread_messages'] ?? 0)
.toList();
var totalUnreadChats = unreadChats.fold<int>(
0,
(previousValue, element) => previousValue + (element as int),
);
controller.add(totalUnreadChats);
});
},
onCancel: () async {
await unreadChatSubscription?.cancel();
},
);
return controller.stream;
}