Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HandleEventsWithSharedFlow
// ViewModel with SharedFlow
abstract class BaseViewModel<STATE, EVENT : UiEvent, EFFECT : UiEffect>(
initialState: UiState<STATE> = UiState.Loading
) : ViewModel() {
...
private val _event: MutableSharedFlow<EVENT> = MutableSharedFlow()
val event = _event.asSharedFlow()
abstract fun handleEvent(event: EVENT)
...
}
// And how to pass info to ViewModel to handle the event
abstract class BaseFragment<STATE, EVENT : UiEvent, EFFECT : UiEffect,
VM : BaseViewModel<STATE, EVENT, EFFECT>, VDB : ViewDataBinding>(
@LayoutRes private val layoutId: Int,
vmKClass: KClass<VM>
) : Fragment() {
...
@InternalCoroutinesApi
final override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(viewModel) {
event
.onEach { handleEvent(it) }
.observeInLifecycle(viewLifecycleOwner)
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment