Performance improvement for chat search filtering (#188)
This commit is contained in:
1 file changed
+33
-9
@@ -1018,22 +1018,46 @@ class ChatViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var searchJob: Job? = null
|
||||||
|
|
||||||
fun setSearchQuery(query: String) {
|
fun setSearchQuery(query: String) {
|
||||||
val messages = _uiState.value.messages
|
searchJob?.cancel()
|
||||||
val indices =
|
|
||||||
if (query.isNotBlank()) {
|
if (query.isBlank()) {
|
||||||
messages.indices.filter { idx ->
|
|
||||||
messages[idx].content.contains(query, ignoreCase = true)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
emptyList()
|
|
||||||
}
|
|
||||||
_uiState.update {
|
_uiState.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
searchQuery = query,
|
searchQuery = query,
|
||||||
|
searchMatchIndices = emptyList(),
|
||||||
|
currentSearchMatchIndex = -1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep local state in sync immediately so UI feels responsive.
|
||||||
|
_uiState.update {
|
||||||
|
it.copy(searchQuery = query)
|
||||||
|
}
|
||||||
|
|
||||||
|
searchJob =
|
||||||
|
viewModelScope.launch(Dispatchers.Default) {
|
||||||
|
val messages = _uiState.value.messages
|
||||||
|
val indices =
|
||||||
|
messages.indices.filter { idx ->
|
||||||
|
messages[idx].content.contains(query, ignoreCase = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
_uiState.update {
|
||||||
|
// Only update indices if the search query hasn't changed in the meantime
|
||||||
|
if (it.searchQuery == query) {
|
||||||
|
it.copy(
|
||||||
searchMatchIndices = indices,
|
searchMatchIndices = indices,
|
||||||
currentSearchMatchIndex = if (indices.isNotEmpty()) 0 else -1,
|
currentSearchMatchIndex = if (indices.isNotEmpty()) 0 else -1,
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
it
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user