b

    Bradleycorn

    1 year ago
    Hi All! I'm working with
    derivedStateOf
    and wondering if there is any difference between the following 2 examples? Is one approach "better" than the other? Are there problems with one approach or the other? Is there an advantage to one over the other (other than just the amount of code)? Is example 2 a proper use of
    derivedStateOf
    ? Am I likely to run into concurrency issues?
    EXAMPLE 1
    
    var UiState by mutableStateOf(MyCompositeDataClass(value1 = null, value2 = null))
       private set
    
    init  {
        viewModelScope.launch {
            getValue1Flow().collect { UiState = UiState.copy(value1 = it) }
        }
    
        viewModelScope.launch {
            getValue2Flow().collect { UiState = UiState.copy(value2 = it) }
        }
    }
    EXAMPLE 2
    
    private var state1 by mutableStateOf<String?>(null)
    private var state2 by mutableStateOf<String?>(null)
    
    val UiState by derivedStateOf {
        UiState(value1 = state1, value2 = state2)
    }
    
    init  {
        viewModelScope.launch {
            getValue1Flow().collect { state1 = it }
        }
    
        viewModelScope.launch {
            getValue2Flow().collect { state2 = it }
        }
    }
    Adam Powell

    Adam Powell

    1 year ago
    Either of these approaches will work, it's more of a matter of formatting your data and code for consumption
    I probably wouldn't use approach 2 unless other things were also individually consuming
    state1
    and
    state2
    or if other derived states mashed up other sets of them; otherwise it sets up quite a bit of machinery and brings additional state vars into scope that aren't really necessary and are kind of noisy
    in approach 1 I would probably use the
    .combine
    operator to merge the flows and keep only one launched coroutine modifying uiState; with
    viewModelScope
    you can get away with it the way it's written above since it's a single-threaded dispatcher, but it's kind of a janky habit to get into
    b

    Bradleycorn

    1 year ago
    Thanks @Adam Powell. I have a few different "real life" use cases that are bit more complex that the example I posted (for example I have one case where I do have multiple things consuming "state1"), but your comments make sense. In simpler cases, I agree that maintaining multiple
    state
    objects (Ex 2) is just more moving parts to maintain.
    Adam Powell

    Adam Powell

    1 year ago
    Sounds like you've got the right of it then 🙂