Skip to content

Instantly share code, notes, and snippets.

/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@Composable
fun AuthorRoute(
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
viewModel: AuthorViewModel = hiltViewModel()
) {
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@Composable
fun AuthorRoute(...) {
val lifecycle = LocalLifecycleOwner.current.lifecycle
val uiState by produceState<AuthorScreenUiState>(
initialValue = viewModel.uiState.value
key1 = lifecycle
key2 = viewModel
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
// app/build.gradle file
dependencies {
implementation "androidx.lifecycle:lifecycle-runtime-compose:2.6.0"
}
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
fun AuthorRoute(
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
viewModel: AuthorViewModel = hiltViewModel()
) {
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
//////////////////////////////////////////////
// Jetpack Compose code
//////////////////////////////////////////////
@Composable
fun MakePaymentScreen(
onPaymentMade: (PaymentModel, Boolean) -> Unit,
/* 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
)
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
//////////////////////////////////////////////
// Jetpack Compose code
//////////////////////////////////////////////
@Composable
fun MakePaymentScreen(
onPaymentMade: (Boolean) -> Unit,
/* 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
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
// FRAGMENTS CODE CONSUMING THE EVENT WRAPPER SOLUTION
- class AddEditTaskFragment : Fragment() {
- override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
- ...
- viewModel.snackbarText.observe(
- lifecycleOwner,
/* Copyright 2022 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
class AddEditTaskViewModel(
private val tasksRepository: TasksRepository
) : ViewModel() {
- private val _snackbarText = MutableLiveData<Event<Int>>()
- val snackbarText: LiveData<Event<Int>> = _snackbarText