Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkOnMainThreadException when used as a LaunchedEffect key

When I use

 LaunchedEffect(Dispatchers.IO) 

I get,

NetworkOnMainThreadException

How should I use this function to run on background thread?

this is my code:

LaunchedEffect(Dispatchers.IO) {
    val input = URL("https://rezaapp.downloadseriesmovie.ir/maintxt.php").readText()
    println(input)
}

I'm using it inside my jetpack compose project

like image 978
Reza Zeraati Avatar asked Oct 21 '25 06:10

Reza Zeraati


1 Answers

You should take a look at what LaunchedEffect does first. In your code, you placed Dispatchers.IO as the key and not as the Dispatcher to use.

Since LaunchedEffect will have a block of CoroutineScope.() -> Unit, you can switch thread within this block like the following :

LaunchedEffect {
    launch(Dispatchers.IO) {
        val input = URL("https://rezaapp.downloadseriesmovie.ir/maintxt.php").readText()
        println(input)
    }
}

Hopefully this is what you are looking for.

like image 63
Jimmy Avatar answered Oct 23 '25 21:10

Jimmy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!