Created
July 14, 2021 19:38
-
-
Save k0siara/dd742b750ac55737e97430b47b9ed0bb to your computer and use it in GitHub Desktop.
CollectingFlowExample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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