Home > Mobile >  How to avoid default value in MutableStateFlow kotlin
How to avoid default value in MutableStateFlow kotlin

Time:06-10

I am using MutableStateFlow in my project. When we initialise the MutableStateFlow object we need to give default value.

val topics = MutableStateFlow<List<String>>(emptyList())

when I collect this value

[null, "Hello", "world"]

I want to pass this list in adapter . So is there a way we can remove the null object before passing in adapter or Is there any better way ?

viewModel.topics.collect { topicsList ->
    println(topicsList)         // [null, "Hello", "world"]
    adapter.submitList(topicsList)
}

CodePudding user response:

If you don't want it to have an enforced initial value, use MutableSharedFlow instead. If you give it replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST, and distinctUntilChanged(), it's basically the same thing as a MutableStateFlow without the enforced value. And if onBufferOverflow is not BufferOverflow.SUSPEND, tryEmit will always succeed so you can use tryEmit() instead of value = .

private val _topics = MutableSharedFlow<List<String>>(
    replay = 1,
    onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val topics: Flow<List<String>> = _topics.distinctUntilChanged()

// emitting to the shared flow:
_topics.tryEmit(newValue)

CodePudding user response:

I think what you need is this:

val sampleList = listOf(null, "Hello", "world")
val topics = MutableStateFlow<List<String>>(sampleList.filer { it != null })
  • Related