https://kotlinlang.org logo
Title
v

Vivek Modi

06/09/2022, 3:03 PM
Hey guys, 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)
}
d

Desmond Teo

06/09/2022, 3:24 PM
is this what you want?
adapter.submitList(topicsList.filterNotNull())
v

Vivek Modi

06/09/2022, 3:25 PM
Yes but if I add this line is do again check in whole list ?
So does it impact on performance?
e

Erick Sumargo

06/09/2022, 3:31 PM
I think you always need to filter those null value manually because it came from the data source (I suppose?). Also if you concern with the performance, perhaps you can move the filter computation to other dispatcher first. Something like this:
viewModel.topics
    .filter { ... }
    .flowOn(Dispatcher.Default)
    .collect { ... }
v

Vivek Modi

06/09/2022, 3:37 PM
Okk great. Thanka
d

DALDEI

06/19/2022, 8:11 AM
I would be interested in how this turns out. My guess is that adding flowOn() actually takes longer (in terms of CPU time used on main thread) due to the overhead of having to dispatch in and out of another thread each time vs simply comparing for nulls It would depend on how big topicList is. My 'guess' is that it would take a list > several 1000's long before it was less time (cpu time used in main thread) to switch threads and back vs filtering inline .