Hi everyone, hope you are all doing well. I am int...
# flow
d
Hi everyone, hope you are all doing well. I am interested in how you manage states when using
StateFlow
. For example, I would usually have a state and something like the following
Copy code
sealed class MyState{
   data class Success(
        val intList: List<Int>
        ....
   ) : MyState()
   data class Success2(
        ....
   ) : MyState()
}
Now when updating my state using
update
Copy code
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 approach
Note: this is a function I use for now
Copy code
inline fun <T, reified Subtype : T> MutableStateFlow<T>.updateIf(function: (Subtype) -> T) {
    update { currentState ->
        if (currentState is Subtype) {
            function(currentState)
        } else currentState
    }
}