Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active June 29, 2022 12:19
Show Gist options
  • Save manuelvicnt/444150940cbc7406e1a03fb2419620cc to your computer and use it in GitHub Desktop.
Save manuelvicnt/444150940cbc7406e1a03fb2419620cc to your computer and use it in GitHub Desktop.
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
//////////////////////////////////////////////
// Jetpack Compose code
//////////////////////////////////////////////
@Composable
fun MakePaymentScreen(
onPaymentMade: (Boolean) -> Unit,
viewModel: MakePaymentViewModel = viewModel()
) {
val currentOnPaymentMade by rememberUpdatedState(onPaymentMade)
val lifecycle = LocalLifecycleOwner.current.lifecycle
// Check whenever navigateToPaymentResultScreen emits a new value
// to tell the caller composable the payment was made
LaunchedEffect(viewModel, lifecycle) {
lifecycle.repeatOnLifecycle(state = STARTED) {
viewModel.navigateToPaymentResultScreen.collect { isPaymentSuccessful ->
currentOnPaymentMade(isPaymentSuccessful)
}
}
}
// Rest of the UI for the make payment 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.navigateToPaymentResultScreen.collect { isPaymentSuccessful ->
val intent = Intent(this, PaymentResultActivity::class.java)
intent.putExtra("PAYMENT_RESULT", isPaymentSuccessful)
startActivity(intent)
finish()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment