Hey people, I’ve got a question about collecting t...
# android
m
Hey people, I’ve got a question about collecting the state from the VM in compose: which one of these is best practice to follow?
Copy code
private val _uiState: MutableStateFlow<UiState> = MutableStateFlow(State.loading())
    val uiState: StateFlow<UiState> = _uiState

    init {
        viewModelScope.launch {
            repository.getData()
                .map { resource ->
                    Log.d("VM", "got $resource")
                    State.fromResource(resource)
                }
                .collect { state -> _uiState.value = state }
        }
    }
or
Copy code
val uiState = repository.getData()
        .map { resource ->
            Log.d("VM", "got $resource")
            State.fromResource(resource)
        }
        .stateIn(
            scope = viewModelScope,
            started = WhileSubscribed(5000),
            initialValue = State.loading()
        )
And calling them from the activity
Copy code
val state by viewModel.uiState.collectAsState()
I am also noticing some heavy delay when the api is executed:
Copy code
I/Choreographer: Skipped 136 frames!  The application may be doing too much work on its main thread.
a
I'd prefer the stateIn+WhileSubscribed approach as it won't stay running when it doesn't have active observers
🙏 1
As for the choreographer warning, it looks like some of your implementation details may need to be moved off the main thread