Executing a callback only when reaching a certain state without user interactions

Viewed 47

Our app receives a notification with a PendingIntent that when clicked, opens the following screen:

@Composable
fun IntermediateMonthlyBillings(
    onDataAcquired: (AllStatementsByYear) -> Unit,
    myEwayLoggedInViewModel: MyEwayLoggedInViewModel = get()
) {
    val statementsByYear by myEwayLoggedInViewModel.statementsByYear.observeAsState(null)
    
    if (statementsByYear == null) {
        GenericLoader(type = MyLoaderType.LIGHT_BACKGROUND)
    } else {
        Button(onClick = { onDataAcquired(statementsByYear!!) }) {
            Text("hi")
        }
    }
}

The screen makes an API call to gather some data and at some point, the statementsByYear will be non-null. When that state is reached, I want to call the onDataAcquired() callback which will lead to a navigation instruction in the end. I need this to happen automatically but a simple if(statementsByYear != null) onDataAcquired() won't work since this will be triggered constantly. I couldn't find a side-effect that works for me either. Can you point me in the right direction?

In the example below I've added the button simply for testing that when used this way, everything works fine since the callback is triggered only once (upon clicking the button). The issue is how can I achieve this without the need for interactions.

1 Answers

LaunchedEffect with statementsByYear == null key would run twice . First when statement is true then it changes to false

LaunchedEffect(statementsByYear == null) {

   if (statementsByYear == null) {
        GenericLoader(type = MyLoaderType.LIGHT_BACKGROUND)
    } else {
       onDataAcquired(statementsByYear!!) 
    }
}

Although answer above is correct, instead of placing a Composable inside LaunchedEffect, it's a remember under the hood, i would go with

LaunchedEffect(statementsByYear != null) {

   if (statementsByYear != null) {
         onDataAcquired(statementsByYear!!) 
   } 
}

if (statementsByYear == null) {
   GenericLoader(type = MyLoaderType.LIGHT_BACKGROUND)
}
Related