Skip to content

Instantly share code, notes, and snippets.

@k0siara
Created July 14, 2021 20:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0siara/7008277243d085636e262bea650cbe47 to your computer and use it in GitHub Desktop.
Save k0siara/7008277243d085636e262bea650cbe47 to your computer and use it in GitHub Desktop.
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