1

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.

Stelios Papamichail
  • 955
  • 2
  • 19
  • 57

1 Answers1

1

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)
}
Thracian
  • 43,021
  • 16
  • 133
  • 222
  • How `First when statement is true then it changes to false` how this will be false and condition inside launcheffect will be true when `abx==null` ? – Kotlin Learner Sep 28 '22 at 07:57
  • `LaunchedEffect(statementsByYear != null)` calls block inside when statement is true or false. Initially when it was null then it changes from null to not null or not null to now. When it's null if block inside LaunchedEffect doesn't get called. When it's not null `LaunchedEffect` is run again since it's not null now `if block` is invoked – Thracian Sep 28 '22 at 08:20
  • okk get it now. Thanks – Kotlin Learner Sep 28 '22 at 09:23