The issue was caused by how the ViewModel was declared in Koin. Using:
single<UserChatViewModel>(createdAtStart = false) { UserChatViewModel(get(), get()) }
creates a singleton ViewModel. When you first open the composable, it works fine. But when the composable is removed from the backstack, Jetpack Compose clears the ViewModel’s lifecycle, which cancels all coroutines in viewModelScope
. Since the singleton instance remains, revisiting the composable uses the same ViewModel whose coroutine scope is already cancelled, so viewModelScope.launch
never runs again.
Changing it to:
viewModelOf(::UserChatViewModel)
ties the ViewModel to the composable lifecycle. Compose clears the old ViewModel when navigating away and creates a new instance when revisiting. This ensures a fresh viewModelScope
for coroutines, and your getAllUsersWithHint()
function works every time.