Vivek Modi
03/29/2025, 7:45 PMVivek Modi
03/29/2025, 7:45 PMimport androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
sealed class ProfileAction {
object OnChangePasswordClick : ProfileAction()
}
class ProfileViewModel : ViewModel() {
// Define a Channel to send actions
private val eventChannel = Channel<ProfileAction>()
val events = eventChannel.receiveAsFlow()
// Function to send actions to the channel
fun onAction(action: ProfileAction) {
viewModelScope.launch {
Log.e("ProfileViewModel", "onAction: $action") // This prints only once
eventChannel.send(action)
}
}
}
Vivek Modi
03/29/2025, 7:45 PMimport android.util.Log
import androidx.compose.runtime.Composable
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun ProfileScreen(profileViewModel: ProfileViewModel = viewModel()) {
// Collect the events as a state (with lifecycle awareness)
val events by profileViewModel.events.collectAsStateWithLifecycle(initial = "")
when (events) {
is ProfileAction.OnChangePasswordClick -> {
Log.e("ProfileScreenRoute", "OnChangePasswordClick") // This keeps printing continuously
updateChangePassword()
}
}
// Button to trigger the action
Button(onClick = { profileViewModel.onAction(ProfileAction.OnChangePasswordClick) }) {
Text("Change Password")
}
}
Vivek Modi
03/29/2025, 7:45 PMLog.e("ProfileViewModel", "onAction: $action")
in the ViewModel prints only once when an action is sent.
• However, Log.e("ProfileScreenRoute", "OnChangePasswordClick")
in the Compose function keeps printing continuously whenever the UI recomposes.
What’s the problem here, and how can I fix it?
I believe the issue is that using collectAsStateWithLifecycle
leads to the state getting recomposed, causing the event to be handled repeatedly. What’s the best way to properly handle one-time events with Compose and a Channel
without causing continuous recompositions?Chrimaeon
03/29/2025, 8:07 PMVivek Modi
03/29/2025, 8:08 PMChrimaeon
03/29/2025, 8:10 PMVivek Modi
03/29/2025, 8:33 PMColton Idle
03/31/2025, 12:36 PM