How would I go about calling a suspend function wi...
# compose
b
How would I go about calling a suspend function within a button onClick action?
Copy code
@Composable
fun LegalBodyContent(contentPadding: InnerPadding = InnerPadding(), onLegal: () -> Unit) {
  val loader = remember { LegalLoader() }

  val networkService = ActiveAppContainer.current.networkService

  launchInComposition {
    loader.load(networkService)
  }

  Crossfade(current = loader.state) { loaderState ->
    when (loaderState) {
      is LegalLoader.State.Loading -> LegalBodyContentLoading()
      is LegalLoader.State.Loaded -> LegalBodyContentLoaded(loaderState)
      is LegalLoader.State.Error -> LegalBodyContentError(loaderState)
    }
    Button(onClick = {
      // How to call loader.load() in here?
    }) {
      Text("Refresh")
    }
  }
}
This is how I’ve currently configured my composable
a
Use
rememberCoroutineScope
to get a scope in composition and launch into it in your click handler
b
Copy code
val scope = rememberCoroutineScope()
  launchInComposition(scope) {
    loader.load(networkService)
  }
and then in the onClick:
Copy code
scope.async { loader.load(networkService) }
Gives me
Deferred result is never used
z
Probably because you’re not using the result. Use
launch
, not
async
.
1