Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

isImeVisible Causes State Loss


I am trying to observe the state of keyboard visibility in my chat app to scroll the lazy column containing my messages to the bottom when the keyboard appears. For that I am storing WindowInsets.isImeVisible like so:

@OptIn(ExperimentalLayoutApi::class)
@Preview(showBackground = true)
@Composable
fun ChatScreen(viewModel: ChatScreenViewModel = ChatScreenViewModel()) {

    val messages = viewModel.messageListState
    val listState = viewModel.messageListScrollState
    val keyboardVisibility = WindowInsets.isImeVisible


        Column(.....)

and here are the ViewModel properties for context:

class ChatScreenViewModel: ViewModel() {

    val messageListScrollState = LazyListState()
    val textFieldState = mutableStateOf("")
    val messageListState = mutableStateListOf<String>(
            "dummy message 1",
            "dummy message 2",
            "dummy message 3",
            "dummy message 4"
        )

The problem is that whenever the isImeVisible is triggered (e.g., I tap on the TextField, keyboard appears, I type something, then hide the keyboard) all the states including textFieldState and messageListState are reset to their original values and lose their updated values. Even holding the isImeVisible value inside a variable seems to cause the issue and things only go back to normal when I completely remove it from my code.

enter image description here


Solution

  • Changing the ViewModel instantiation method to the one below seems to have fixed the issue:

    import androidx.lifecycle.viewmodel.compose.viewModel
    
    fun ChatScreen(viewModel: ChatScreenViewModel = viewModel())