简体   繁体   English

如何处理 Jetpack Compose 中的回调?

[英]How to handle callbacks in Jetpack compose?

I am migrating my multiple activity app to single activity app.我正在将我的多活动应用程序迁移到单活动应用程序。

In the activity I am observing a live data from view model. When the observable triggers, I start a payment activity from a third party SDK as shown below.在活动中,我正在观察来自视图 model 的实时数据。当可观察触发时,我从第三方 SDK 开始支付活动,如下所示。


onCreate() {
  viewmodel.orderCreation.observe {
    thirdpartysdk.startPaymentWithThisOrder(context)
  }
}


onActivityResult() {
  // use payment result
}

As I will be using a Composable now,因为我现在将使用 Composable,

@Composable
fun PaymentScreen(onOrderCreated: () -> Unit) {
   val orderCreation by viewmodel.orderCreation.observeAsState()
   
   // How to use order creation once here to call onOrderCreated here only once as composable is called again and again
}

Here's my suggestion:这是我的建议:

In your viewmodel, create a function to reset your orderCreation .在您的视图模型中,创建一个 function 来重置您的orderCreation And another field + function to store the payment result.还有一个字段+function,用来存放支付结果。

Something like:就像是:

fun resetOrderCreation() {
    _orderCreation.value = null
}

fun paymentResult(value: SomeType) {
    _paymentResult.value = value
}

Now, in your composable, you can do the following:现在,在您的可组合项中,您可以执行以下操作:

@Composable
fun PaymentScreen(onOrderCreated: () -> Unit) {
    // 1
    val orderCreation by viewmodel.orderCreation.observeAsState()
    var paymentResult by viewmodel.paymentResult.observeAsState()
    // 2  
    val launcher = rememberLauncherForActivityResult(
        PaymentActivityResultContract()
    ) { result ->
        viewModel.paymentResult(result)
    }

    ...
    // 3
    LaunchedEffect(orderCreation) {
        if (orderCreation != null) {
            launcher.launch()
            viewModel.resetOrderCreation()
        }
    }
    // 4
    if (paymentStatus != null) {
        // Show some UI showing the payment status
    }
}

Explaining the code:解释代码:

  1. I'm assuming that you're using LiveData .我假设您正在使用LiveData But I really suggest you move to StateFlow instead.但我真的建议您StateFlow See more here . 在这里查看更多。
  2. You will probably need to write a ActivityResultContact to your third party lib.您可能需要将ActivityResultContact写入第三方库。 I wrote a post about (it's in Portuguese, but I think you can get the idea translating it to English).我写了一篇关于(它是葡萄牙语,但我想你可以把它翻译成英语的想法)。
  3. As soon the orderCreation has changed, the LaunchedEffect block will run, then you can start the third party activity using launcher.launch() (the parameters for this call are defined in your ActivityResultContract ).一旦orderCreation发生变化, LaunchedEffect块将运行,然后您可以使用launcher.launch()启动第三方活动(此调用的参数在您的ActivityResultContract中定义)。
  4. Finally, when the payment status changed, you can show something different to the user.最后,当付款状态发生变化时,您可以向用户显示不同的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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