Implementing MVI with Kotlin flows
In this section, we will look at how we can implement the MVI architecture pattern using Kotlin flows and the benefits and pitfalls of this approach.
In the previous section, we defined an MVI approach using StateFlow
and SharedFlow
, as in the following example:
private val _myStateFlow = MutableStateFlow<MyState>(MyState()) val myStateFlow: StateFlow<MyState> = _myDataFlow private val actionFlow: MutableSharedFlow<MyAction> = MutableSharedFlow()
The different types of flows used here serve different purposes. MutableStateFlow
will emit the last value held, which is good for the user interface because we want it to display the last data loaded, like how LiveData
works. SharedFlow
doesn't have this feature, which is useful for actions because we do not want the last action to be emitted twice. Another aspect we will need to consider is one-shot events...