Thread
#compose
    m

    Mohamed Elfiky

    2 years ago
    so i have code like the below with a class represents the whole state of the screen and observing it in the root compose of that screen. is this a bad design from what i saw when i watched leland that the compose compiler is smart enough or will be to know when to recompose. second is using MutableStateFlow or mutableStateOf make any diffrence?
    enum class Sort {
        ownerName,
        taskTitle,
        size
    }
    
    sealed class UiState {
        object Loading : UiState()
        data class Success(
            val data: List<Int>,
            val sortExpanded: Boolean = false,
            val sort: Sort = Sort.ownerName,
        ) : UiState()
        object Error : UiState()
    }
    
    class UiViewModel(repo: Repo) : ViewModel() {
    
        // private val _state = MutableStateFlow<UiState>(UiState.Loading)
        // val state: StateFlow<UiState> get() = _state
        var state by mutableStateOf<UiState>(UiState.Loading)
        private set
    
        fun toggleSortDialog() {}
        ....
    }
    
    @Composable
    fun RootScreenUi() {
        val viewModel = viewModel<UiViewModel>()
        val state = viewModel.state
    
       ....
    }
    John O'Reilly

    John O'Reilly

    2 years ago
    re.
    mutableStateOf
    vs
    MutableStateFlow
    https://developer.android.com/codelabs/jetpack-compose-state provides some guidance on that.....the recommendation is to use first one if view model is used only by Compose (and is only really usable in that context)
    Archie

    Archie

    2 years ago
    second is using MutableStateFlow or mutableStateOf make any diffrence?
    • I believe no, to listen a
    MutableStateFlow
    in compose you would have to convert it to
    State<T>
    anyway, making it work the same way.
    compose compiler is smart enough or will be to know when to recompose
    • ill try to answer but you should probably wait for some other else answer you on this one to make sure, by "is smart enough to know", it dependes on the value of your state.. it knows when to recompose when the value of your state changes. Now, if you place you state way above the your composable, all composable who listens to that state would get recomposed everytime that state value changes. I believe (and please correct me if Im wrong) you would want to minimize the number of recomposition in your composable tree.
    m

    Mohamed Elfiky

    2 years ago
    @John O'Reilly thanks i believe it make sense
    @Archie thanks for your answer but what i have seen that the parent component which i use when statement on the are the only ones that change all the time but there children changes only when the value changes