简体   繁体   中英

How can I launch a function only onetime when I use Jetpack Compose?

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))
        }   
        
        ...     
    }
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM