StateFlow causing navigation loop in Jetpack Compose

Viewed 223

There are two screens in the app. Screen A and Screen B. The UI and navigation logic of Screen A is based on the state class.

ScreenAState

data class ScreenAState(
    val sourceName: String = "",
    val navigateToScreenB: Boolean = false
)

If the user meets the requirements, the value of navigateToScreenB is changed to true and the user is navigated to Screen B using the following code.

if (uiState.navigateToScreenB) {
     LaunchedEffect(uiState.navigateToScreenB) {
          findNavController().navigate(actionToScreenB)
        }
    }

Now, the problem occurs when the user presses the back button on Screen B. As soon as the user comes back from Screen B to Screen A, the user is again navigated to Screen B and the loop continues if the back button is pressed again on Screen B.

I am not sure if I am using the LaunchedEffect properly. Any help will be appreciated. Thank You.

1 Answers

You should set navigateToScreenB to false after perform the navigation. Declaring something like this in your view model.

class YourViewModel: ViewModel() {
    private val _uiState = MutableStateFlow(ScreenAState())
    val uiState = _uiState.asStateFlow()

    fun onNavigateToScreenB() {
        uiState.update {
            it.copy(navigateToScreenB = false)
        }
    }
    ...
}    

and in your screen:

val uiState by yourViewModel.uiState.collectAsState()
if (uiState.navigateToScreenB) {
    LaunchedEffect(uiState.navigateToScreenB) {
        viewModel.onNavigateToScreenB()
        findNavController().navigate(actionToScreenB)
    }
}
Related