How do I call a suspend function (network call) wh...
# android
l
How do I call a suspend function (network call) when initializing my main activity? This is what I've got (from the tutorial) and it shows a blank page. I've even tried changing the return from the function to a simple string instead of making a call and get the same. There's no build or runtime red errors
Copy code
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    val scope = rememberCoroutineScope()
                    var text by remember { mutableStateOf("Loading") }
                    LaunchedEffect(true) {
                        scope.launch {
                            text = try {
                                Greeting().greeting()
                            } catch (e: Exception) {
                                e.localizedMessage ?: "error"
                            }
                        }
                    }
                    Greeting(text)
                }
            }
        }
    }
}
z
LaunchedEffect
already starts a coroutine for you, so you shouldn't need to create a scope and use
launch
. Just make your suspending calls within the suspending function that you're passing to
LaunchedEffect
.
l
I am, I'm narrowing the issue down to the API call made, as I've fixed the suspend issue using a lifecycle coroutine to make absolutely sure the problem isn't elsewhere. If this piece of code runs, no result will appear. I can use a
delay(3000)
in its place and it WILL run then. So I'm guessing I messed up using Ktro somehow
Copy code
val rockets: List<RocketLaunch> =
            httpClient.get("<https://api.spacexdata.com/v4/launches>").body()
        val lastSuccessLaunch = rockets.last { it.launchSuccess == true }
It's really odd, it just suddenly started to work after removing and adding those lines and a few restarts. Maybe the emulator or gradle didn't build something right? Very strange, maybe it will even work with the original code now!
Ok, SOMETIMES the network call works and sometimes it fails silently. This is so weird