read method
- ChatItemId untilId
Marks this RxChat as read until the provided ChatItem for the authenticated MyUser,
Implementation
Future<void> read(ChatItemId untilId) async {
Log.debug('read($untilId)', '$runtimeType($id)');
int firstUnreadIndex = 0;
if (firstUnread != null) {
firstUnreadIndex = messages.indexOf(firstUnread!);
}
int lastReadIndex = messages.indexWhere(
(m) => m.value.id == untilId,
firstUnreadIndex,
);
if (lastReadIndex != -1 && firstUnreadIndex != -1) {
int read =
messages
.skip(firstUnreadIndex)
.take(lastReadIndex - firstUnreadIndex + 1)
.where((e) => !e.value.id.isLocal && e.value.author.id != me)
.length;
unreadCount.value = chat.value.unreadCount - read;
}
final ChatItemId? lastReadItem = chat.value.lastReadItem;
if (lastReadItem != untilId) {
chat.update((e) => e?..lastReadItem = untilId);
_readTimer?.cancel();
_readTimer = AwaitableTimer(
chat.value.lastItem?.id == untilId
? Duration.zero
: const Duration(seconds: 1),
() async {
try {
await _chatRepository.readUntil(id, untilId);
final DtoChatItem? item = await _driftItems.read(untilId);
_lastReadItemCursor =
item?.cursor ?? _lastReadItemCursor ?? dto.lastReadItemCursor;
dto.lastReadItemCursor = _lastReadItemCursor;
} catch (_) {
chat.update((e) => e?..lastReadItem = lastReadItem);
unreadCount.value = chat.value.unreadCount;
rethrow;
} finally {
_readTimer = null;
}
},
);
await _readTimer?.future;
}
}