Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active February 27, 2023 16:55
Show Gist options
  • Save manuelvicnt/e6b25f4cf70562759659e0599e004633 to your computer and use it in GitHub Desktop.
Save manuelvicnt/e6b25f4cf70562759659e0599e004633 to your computer and use it in GitHub Desktop.
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
data class MakePaymentUiState(
val paymentInformation: PaymentModel,
val isLoading: Boolean = false,
// PaymentResult models the application state of this particular payment attempt,
// `null` represents the payment hasn't been made yet.
val paymentResult: PaymentResult? = null
)
class MakePaymentViewModel(...) : ViewModel() {
private val _uiState = MutableStateFlow<MakePaymentUiState>(...)
val uiState: StateFlow<MakePaymentUiState> = _uiState.asStateFlow()
// Protecting makePayment from concurrent callers
// If a payment is in progress, don't trigger it again
private var makePaymentJob: Job? = null
fun makePayment() {
if (makePaymentJob != null) return
makePaymentJob = viewModelScope.launch {
try {
_uiState.update { it.copy(isLoading = true) }
val isPaymentSuccessful = paymentsRepository.makePayment(...)
// The event of what to do when the payment response comes back
// is immediately handled here. It causes a UI state update.
_uiState.update {
it.copy(
isLoading = false,
paymentResult = PaymentResult(it.paymentInfo, isPaymentSuccessful)
)
}
} catch (ioe: IOException) { ... }
finally { makePaymentJob = null }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment