hi all :wave: are there any implications if I upda...
# android
g
hi all 👋 are there any implications if I update/render the state of the UI using another Dispatcher and not the Main one?
m
Depends on what you mean by updating the state of the UI. If you are talking about changing properties on a
View
object, that must happen on the main thread. Pretty much all interaction with
Views
must be on the main thread. If you are talking about changing some state property like with MVVM, then it depends on the thread safety of that and how that eventually gets to the UI. For Compose, you don't directly interact with the UI but instead with just state, so it depends on what you are using for storing the state.
☝️ 1
g
> If you are talking about changing some state property like with MVVM yes. Let's say that my repository does the work in IO Dispatcher and then I collect from viewmodel and update a simple state with some primitives and one List. If I
flowOn
the collection (in the viewmodel) with a default dispatcher then what are the implications there?
m
It depends on how your view model state is stored and read.
g
Copy code
sealed interface ExampleUiState : UiState {

        data object Loading : ExampleUiState

        data class Data(
            val accounts: Set<Account> // Account is a data class with three string properties
        ) : ExampleUiState
    }
let's assume this simple state
m
It depends on how you are sharing that state between the view model and the UI
g
forgive me i should have given a complete example from the begining
Copy code
init {
        myRepository.getAccounts()
            .onEach { accounts ->
                _state.emit(
                    ExampleUiState.Data(
                        accounts = accounts
                    )
                )
            }
            .flowOn(dispatcher) //<- here to use the default dispatcher 
            .launchIn(viewModelScope)
  }
m
what is _state?
g
a state flow
Copy code
protected val _state: MutableStateFlow<T> by lazy { MutableStateFlow(initialState()) }
    val state: StateFlow<T>
        get() = _state.asStateFlow()
m
MutableStateFlow is safe, so it should work fine.
g
however does anything change if i use the default dispatcher there instead of the main?
r
Any reason you don't want to move
flowOn
above
onEach
(or even better inside your implementation of
getAccounts
because it shouldn't be caller's responsibility to know about this)?
plus1 2