# android-architecture

Lokik Soni

06/17/2022, 6:10 PM
Hi I am using clean architecture to develop app but I am confusing in sending states from ViewModel to Compose Screen i.e State to show Sanckbar and State to navigate. I am getting confuse in handling that state in Compose. Please see the code below:
Copy code
data class AddEditNoteState(
   val title: String = "",
   val isNoteSaved: Boolean = false,
   val errorMsg: String? = null
Copy code
class AddEditNoteViewModel @Inject constructor(
   savedStateHandle: SavedStateHandle,
   private val _addNoteUseCase: AddNoteUseCase,
   private val _getNoteById: GetNoteUseCase
): ViewModel() {

   // TODO may not need stateIn
   private val _addEditNoteSate = MutableStateFlow(AddEditNoteState())
   val addEditNoteState = _addEditNoteSate
      .stateIn(viewModelScope, WhileViewSubscribed, AddEditNoteState())

   fun onEvent(addEditNoteEvent: AddEditNoteEvent) {

		when(addEditNoteEvent) {
			is AddEditNoteEvent.SaveNote -> {
				viewModelScope.launch {
					try {
								title = _addEditNoteSate.value.title,
						_addEditNoteSate.update { it.copy(isNoteSaved = true, errorMsg = null,) }

					} catch (e: NoteAppException.InvalidNoteException) {
						_addEditNoteSate.update { it.copy(isNoteSaved = false, errorMsg = e.msg) }
In viewmodel if not saved success I want to navigate back but on error want to show snackbar. So for this should I create two LaunchEffect for navigate and snackbar or it is not good to have two LaunchEffect. In Compose Screen
Copy code
val message = addEditNoteState.errorMsg
message?.let { msg ->
   LaunchedEffect(scaffoldState, msg) {
      scaffoldState.snackbarHostState.showSnackbar(message = msg)
Currently I have handled only snackbar state like above. I want to follow Google recommended one-off ViewModel event.

Colton Idle

06/17/2022, 7:23 PM
one off event from VM is described as an antipattern from google:
the arch docs show an example of how to properly use state for displaying a snackbar