Last active
May 31, 2022 12:27
-
-
Save manuelvicnt/77498149c2fd779e539e264c73a51416 to your computer and use it in GitHub Desktop.
This file contains 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 */ | |
// FRAGMENTS CODE CONSUMING THE EVENT WRAPPER SOLUTION | |
- class AddEditTaskFragment : Fragment() { | |
- override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
- ... | |
- viewModel.snackbarText.observe( | |
- lifecycleOwner, | |
- Observer { event -> | |
- event.getContentIfNotHandled()?.let { | |
- showSnackbar(context.getString(it), Snackbar.LENGTH_SHORT) | |
- } | |
- } | |
- ) | |
- } | |
- } | |
// COMPOSE CODE CONSUMING USER MESSAGES AS STATE | |
// State holder for the AddEditTask composable. | |
// This class handles AddEditTask's UI elements' state and UI logic. | |
+ class AddEditTaskState(...) { | |
+ init { | |
+ // Listen for snackbar messages | |
+ viewModel.snackbarText.observe(viewLifecycleOwner) { snackbarMessage -> | |
+ if (snackbarMessage != null) { | |
+ // If there's a previous message showing on the screen | |
+ // stop showing it in favor of the new one to be displayed | |
+ currentSnackbarJob?.cancel() | |
+ val snackbarText = context.getString(snackbarMessage) | |
+ currentSnackbarJob = coroutineScope.launch { | |
+ scaffoldState.snackbarHostState.showSnackbar(snackbarText) | |
+ viewModel.snackbarMessageShown() | |
+ } | |
+ } | |
+ } | |
+ } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment