Last active
November 12, 2022 09:04
-
-
Save manuelvicnt/9359df79d1a1638a916fab37e7ac0c11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Copyright 2022 Google LLC. | |
SPDX-License-Identifier: Apache-2.0 */ | |
////////////////////////////////////////////// | |
// Jetpack Compose code | |
////////////////////////////////////////////// | |
@Composable | |
fun MakePaymentScreen( | |
onPaymentMade: (PaymentModel, Boolean) -> Unit, | |
viewModel: MakePaymentViewModel = viewModel() | |
) { | |
val uiState by viewModel.uiState.collectAsState() | |
uiState.paymentResult?.let { | |
val currentOnPaymentMade by rememberUpdatedState(onPaymentMade) | |
LaunchedEffect(uiState) { | |
// Tell the caller composable that the payment was made. | |
// the parent composable will act accordingly. | |
currentOnPaymentMade( | |
uiState.paymentResult.paymentModel, | |
uiState.paymentResult.isPaymentSuccessful | |
) | |
} | |
} | |
// Rest of the UI for the login screen. | |
} | |
////////////////////////////////////////////// | |
// Activity / Views code | |
////////////////////////////////////////////// | |
class MakePaymentActivity : AppCompatActivity() { | |
private val viewModel: MakePaymentViewModel by viewModels() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
/* ... */ | |
lifecycleScope.launch { | |
repeatOnLifecycle(Lifecycle.State.STARTED) { | |
viewModel.uiState.collect { uiState -> | |
if (uiState.paymentResult != null) { | |
val intent = Intent(this, PaymentResultActivity::class.java) | |
intent.putExtra( | |
"PAYMENT_RESULT", | |
uiState.paymentResult.isPaymentSuccessful | |
) | |
startActivity(intent) | |
finish() | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is
rememberUpdatedState
on line 16 of rev 3 necessary? My understanding is that this construct is only necessary if the reference is captured for use at a later time like in a long-running coroutine within the effect. Here the launched effect is evaluated immediately.[Actually I see it is carried over from rev 2 where it did have a purpose when referenced in a lifecycle observer. Perhaps it is no longer needed.]