1

I'm using Network Connectivity Manager,

In this lambda function when "it" value is false the TOAST will show, BUT after once the Wi-Fi is turned on and the value changes to true it automatically navigates to the composable

it shouldn't navigate that way!

        onClick = {
        manager.observe(lifecycleOwner.value) {
            if (!it) {
                Toast.makeText(
                    context,
                    "CHECK YOUR INTERNET CONNECTION",
                    Toast.LENGTH_LONG
                ).show()

            } else {
                navController.navigate(
                    route = "onlinePlayer/${song.songName}/${song.songArtist}" +
                            "/${
                                URLEncoder.encode(
                                    song.link,
                                    StandardCharsets.UTF_8.toString()
                                )
                            }" +
                            "/${
                                URLEncoder.encode(
                                    song.image,
                                    StandardCharsets.UTF_8.toString()
                                )
                            }"
                )
            }
        }
    }
Marwan Talal
  • 107
  • 6
  • 1
    Why do you call `navController.navigate` if you don't want to navigate? – gpunto May 28 '22 at 14:00
  • As a side, "observing" something in a button click is bad design in Compose (and generally this logic is flawed as a new observer is created every click until the lifecycle ends) - this kind of logic should be within a `SideEffect` and more specfically in this case a `DisposableSideEffect` or collected as a `State` object variable within the Composable, which can be referenced within the click lambda. Network can come and go whenever so its better to be reactive, than defensive. – Mark May 28 '22 at 15:21
  • @gpunto I have a button, After the user presses the button, I want to check if the Wi-Fi is off it will show a toast. The issue is: When the user presses the button and the Wi-Fi is off and then he turns the Wi-Fi on once it connects to the internet it navigates automatically!! – Marwan Talal May 29 '22 at 19:45
  • As @Mark is saying, you shouldn't start observing anything on a click. The observer outlives the click, so after the first tap on the button, you will receive any new emission from `manager`. You should do as @Mark suggests, e.g. collecting `manager` as state, probably through `manager.observeAsState()`. – gpunto May 29 '22 at 20:58

0 Answers0