Home > Back-end >  Executing a callback only when reaching a certain state without user interactions
Executing a callback only when reaching a certain state without user interactions

Time:07-01

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.

CodePudding user response:

you can add a state named isTriggered and set it to false by default and only call that callback when isTriggered == false and after the call set isTriggered to true, so the code should look like this.

@Composable
fun IntermediateMonthlyBillings(
    onDataAcquired: (AllStatementsByYear) -> Unit,
    myEwayLoggedInViewModel: MyEwayLoggedInViewModel = get()
) {
    val statementsByYear by myEwayLoggedInViewModel.statementsByYear.observeAsState(null)
    val isTriggered by remember { mutableStateOf(false) }

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

CodePudding user response:

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!!) 
    }
}
  • Related