1

I need to launch mViewMode.iniBilling(context as Activity) first before I launch mViewMode.purchaseProduct(context as Activity) in fun ScreenPurchase.

You know the fun ScreenPurchase may be launched repeatedly when the system needs to refresh UI.

I hope mViewMode.iniBilling(context as Activity) can be launched only one time, how can I do?

@Composable
fun ScreenPurchase(
    onBack: () -> Unit,   
    mViewMode: SoundViewModel,
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        scaffoldState = scaffoldState,
        topBar = { PurchaseAppBar(onBack = onBack) }
    ) { paddingValues ->
       
        val context = LocalContext.current
                
        mViewMode.iniBilling(context as Activity)  //I hope it launched only one time.

        Button(
            modifier = Modifier,
            onClick = {
                mViewMode.purchaseProduct(context as Activity)
            }
        ) {
            Text(stringResource(R.string.btnBuy))
        }   
        
        ...     
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

3

block of LaunchedEffect(keys) is invoked on composition and when any keys change. If you set keys from your ViewModel this LaunchedEffect will be launched and you can create a conditional block that checks same flag to be true that is contained in your ViewModel

LaunchedEffect(mViewModel.isLaunched) {
    if(!mViewModel.isLaunched) {
          mViewMode.iniBilling(context as Activity)
          mViewMode.isLaunched = true
    }
}
Thracian
  • 43,021
  • 16
  • 133
  • 222
  • I am trying to understand this according to your answer. Correct me If I am wrong. When first time composition happens in `ScreenPurchase` then then what value will be in `mViewModel.isLaunched` to launch LaunchedEffect? – Kotlin Learner Jul 20 '22 at 07:30
  • True or false ? – Kotlin Learner Jul 20 '22 at 07:31
  • LaunchedEffect runs runs on composition with initial value of mViewModel.isLaunched whether it's true or false then runs again it changes. But `if(!mViewModel.isLaunched)` checks if it's false to run block inside it. In this question since we want if block to run `mViewModel.isLaunched` should be `false` initially – Thracian Jul 20 '22 at 07:37
  • You can run a LaunchedEffect(true), LaunchedEffect(false), LaunchedEffect(Unit) or with any key or multiple keys. It will run initially then check whether keys you set change to run block again. It's remember under the hood with a coroutineScope and works as remember keys. Sometimes you need to have a LaunchedEffect depends on many things such as Composable color or dimensions change `LaunchedEffect(color, width, height) {...}` – Thracian Jul 20 '22 at 07:39
  • On nice I now I understand correctly. Thanks a million – Kotlin Learner Jul 20 '22 at 07:44
  • can you help me on this [issue](https://stackoverflow.com/q/73051366/11560810) – Kotlin Learner Jul 20 '22 at 12:08