[英]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:解释代码:
LiveData
.LiveData
。 But I really suggest you move to StateFlow
instead.StateFlow
。 See more here . 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).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
中定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.