favoriteChatContact method

  1. @override
Future<void> favoriteChatContact(
  1. ChatContactId id,
  2. ChatContactFavoritePosition? position
)
override

Marks the specified ChatContact as favorited for the authenticated MyUser and sets its position in the favorites list.

Implementation

@override
Future<void> favoriteChatContact(
  ChatContactId id,
  ChatContactFavoritePosition? position,
) async {
  Log.debug('favoriteChatContact($id, $position)', '$runtimeType');

  final RxChatContactImpl? contact = contacts[id];

  final ChatContactFavoritePosition? oldPosition =
      contact?.contact.value.favoritePosition;
  final ChatContactFavoritePosition newPosition;

  if (position == null) {
    final List<RxChatContactImpl> favorites =
        contacts.values
            .where((e) => e.contact.value.favoritePosition != null)
            .toList();

    final List<RxChatContactImpl> sorted = favorites..sort();

    final double? highestFavorite =
        sorted.isEmpty
            ? null
            : sorted.first.contact.value.favoritePosition!.val;

    newPosition = ChatContactFavoritePosition(
      highestFavorite == null ? 1 : highestFavorite * 2,
    );
  } else {
    newPosition = position;
  }

  contact?.contact.update((c) => c?.favoritePosition = newPosition);
  _emit(MapChangeNotification.updated(contact?.id, contact?.id, contact));

  try {
    await _graphQlProvider.favoriteChatContact(id, newPosition);
  } catch (e) {
    contact?.contact.update((c) => c?.favoritePosition = oldPosition);
    _emit(MapChangeNotification.updated(contact?.id, contact?.id, contact));
    rethrow;
  }
}