kotlinkotlin-coroutines

What is the difference between state.asStateFlow() and flow.stateIn()?


There are two equal in my opinion constructions, which of them should be used when and what are the advantages of these methods?

The first is:

private val _chats: MutableStateFlow<List<Chat>> = MutableStateFlow(emptyList())
val chats: StateFlow<List<Chat>> = _chats.asStateFlow()

init {
    viewModelScope.launch {
        repository.chatsFlow.collect { chats ->
            _chats.value = chats
        }
    }
}

The second one:

val chats: StateFlow<List<Chat>> = repository.chatsFlow
    .stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000L),
        initialValue = emptyList()
    )

Solution

  • The MutableStateFlow/asFlow way should be avoided. Aside from being very verbose, it continuously collects the upstream flow even when it doesn't have anything collecting from it, which wastes resources.