Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active June 29, 2022 12:19
Show Gist options
  • Save manuelvicnt/dc42e9bf6d903cfd46c5872eb57ee5b5 to your computer and use it in GitHub Desktop.
Save manuelvicnt/dc42e9bf6d903cfd46c5872eb57ee5b5 to your computer and use it in GitHub Desktop.
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
class MakePaymentViewModel(...) : ViewModel() {
val uiState: StateFlow<MakePaymentUiState> = /* ... */
// ⚠️⚠️ DO NOT DO THIS!! ⚠️⚠️
// This one-off ViewModel event hasn't been handled nor reduced to state
// Boolean represents whether or not the payment was successful
private val _navigateToPaymentResultScreen = Channel<Boolean>()
// `receiveAsFlow` makes sure only one collector will process each
// navigation event to avoid multiple back stack entries
val navigateToPaymentResultScreen = _navigateToPaymentResultScreen.receiveAsFlow()
// 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) } // Show loading spinner
val isPaymentSuccessful = paymentsRepository.makePayment(...)
_navigateToPaymentResultScreen.send(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