refactor: Cache direct chat matrix ID
The direct chat account data content is a map from matrixId to roomId(s). If we want to find the roomId for a given userId, then this is not a problem. But the other way around, if we want to check if a given roomId is a direct chat or not, needs to process all entries which can be hundreds. Doing this very often in an app costs a lot of performance. This adds a simple cache in the room object and validates the cache every time to make this more efficient.
This commit is contained in:
parent
188a4e2596
commit
42f44de2b1
|
|
@ -356,15 +356,27 @@ class Room {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String? _cachedDirectChatMatrixId;
|
||||||
|
|
||||||
/// If this room is a direct chat, this is the matrix ID of the user.
|
/// If this room is a direct chat, this is the matrix ID of the user.
|
||||||
/// Returns null otherwise.
|
/// Returns null otherwise.
|
||||||
String? get directChatMatrixID {
|
String? get directChatMatrixID {
|
||||||
|
// Calculating the directChatMatrixId can be expensive. We cache it and
|
||||||
|
// validate the cache instead every time.
|
||||||
|
final cache = _cachedDirectChatMatrixId;
|
||||||
|
if (cache != null) {
|
||||||
|
final roomIds = client.directChats[cache];
|
||||||
|
if (roomIds is List && roomIds.contains(id)) {
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (membership == Membership.invite) {
|
if (membership == Membership.invite) {
|
||||||
final userID = client.userID;
|
final userID = client.userID;
|
||||||
if (userID == null) return null;
|
if (userID == null) return null;
|
||||||
final invitation = getState(EventTypes.RoomMember, userID);
|
final invitation = getState(EventTypes.RoomMember, userID);
|
||||||
if (invitation != null && invitation.content['is_direct'] == true) {
|
if (invitation != null && invitation.content['is_direct'] == true) {
|
||||||
return invitation.senderId;
|
return _cachedDirectChatMatrixId = invitation.senderId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -373,8 +385,8 @@ class Room {
|
||||||
final roomIds = e.value;
|
final roomIds = e.value;
|
||||||
return roomIds is List<dynamic> && roomIds.contains(id);
|
return roomIds is List<dynamic> && roomIds.contains(id);
|
||||||
})?.key;
|
})?.key;
|
||||||
if (mxId?.isValidMatrixId == true) return mxId;
|
if (mxId?.isValidMatrixId == true) return _cachedDirectChatMatrixId = mxId;
|
||||||
return null;
|
return _cachedDirectChatMatrixId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wheither this is a direct chat or not
|
/// Wheither this is a direct chat or not
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue