Lokik Soni
06/17/2022, 6:10 PMdata class AddEditNoteState(
val title: String = "",
val isNoteSaved: Boolean = false,
val errorMsg: String? = null
)
ViewModel
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
.asStateFlow()
.stateIn(viewModelScope, WhileViewSubscribed, AddEditNoteState())
fun onEvent(addEditNoteEvent: AddEditNoteEvent) {
when(addEditNoteEvent) {
is AddEditNoteEvent.SaveNote -> {
viewModelScope.launch {
try {
_addNoteUseCase(
Note(
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
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