Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CollectingFlowExample
// ViewModel with some Flows to observe and collect
abstract class BaseViewModel<STATE, EVENT : UiEvent, EFFECT : UiEffect>(
initialState: UiState<STATE> = UiState.Loading
) : ViewModel() {
...
private val _uiState: MutableStateFlow<UiState<STATE>> = MutableStateFlow(initialState)
val uiState = _uiState.asStateFlow()
private val _event: MutableSharedFlow<EVENT> = MutableSharedFlow()
val event = _event.asSharedFlow()
private val _effect: Channel<EFFECT> = Channel()
val effect = _effect.receiveAsFlow()
abstract fun handleEvent(event: EVENT)
...
}
// And how to collect them in the Fragment
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)
uiState
.onEach { handleState(it) }
.observeInLifecycle(viewLifecycleOwner)
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment