Djuro
04/11/2024, 8:16 AMStateFlow
.
For example, I would usually have a state and something like the following
sealed class MyState{
data class Success(
val intList: List<Int>
....
) : MyState()
data class Success2(
....
) : MyState()
}
Now when updating my state using update
myState.update{ currentState ->
if(currentState is MyState.Success){
currentState.copy(intList = newIntList())
} else currentState
}
fun newIntList(): List<Int> {...}
Is there some approach you take to avoid this if/else
branching? I always hated it but didn't figure out yet how to get rid of it.
Do you have some suggestions?
for example, I can make a function myState.updateIf<MyState, MyState.Success>{ mySuccessState -> ... }
but I am unsure if there is some other better approachDjuro
04/11/2024, 8:44 AMinline fun <T, reified Subtype : T> MutableStateFlow<T>.updateIf(function: (Subtype) -> T) {
update { currentState ->
if (currentState is Subtype) {
function(currentState)
} else currentState
}
}