0

I have a problem that I still can't solve and it just doesn't want to work. Basically I have to convert a function into a composable. In the old function I launched a Coroutine and at the result, I changed context and then continued with my processes. In compose I don't understand how I have to "change context" in order to continue. Old code:

 fun getMyView( activity: Activity
) {
     backgroundCoroutineScope.launch {
         //some stuff here

         withContext(coroutineContext) {

             startSearchView(
                 activity
             )
         }
     }

}

New not working code:

 @Composable
 fun getMyView( content: @Composable() () -> Unit) {
         LaunchedEffect(key1 = Unit)  {
             //some stuff here like old funciont

            //here I don't know how to change context, wait the end and go ahead. startSearchViewis a composable function too
            // i want to use it to populate my screen
                 startSearchView(
                     content
                 )
             
         }
    }

How can I solve it? Thanks

DoctorWho
  • 1,044
  • 11
  • 34
  • In Compose you need to manipulate with the state, check out [this answer](https://stackoverflow.com/a/71535932/3585796) for example – Phil Dukhov Apr 12 '22 at 14:21

1 Answers1

0

Seems like you are trying to asynchronously "create" composable function, but UI emitting doesn't work this way. Like @PylypDukhov suggested, you should keep a mutable state holding nullable result of your async action. After loading the data set this state. Then in composable just do something like:

if (data != null) {
    SearchComposable(data) 
}

This way the composable will be emitted after the data is loaded

Jakoss
  • 4,647
  • 2
  • 26
  • 40