Hey guys can we improve this piece of code? ```va...
# codereview
v
Hey guys can we improve this piece of code?
Copy code
val filteredTopics by lazy { MutableStateFlow<List<Topics>>(emptyList()) }
Copy code
val temp = list.filter { it.topics != null }.filter { it.title == value.title }
filteredTopics.value = temp.firstOrNull()?.topics?.sortedBy { topic -> topic.title } ?: emptyList()
d
Hi Vivek, I believe that a small improvement could be to do both filters together, the are pretty small:
Copy code
filteredTopics.value = list.filter { it.topics != null && it.title == value.title }.firstOrNull()?.topics?.sortedBy { topic -> topic.title } ?: emptyList()
I would (and this is 100% personal taste) do it together just with returns and nice spacing
v
Hi @Diego Marzo thank you so much.
🙌 1
e
.filter { ... }.firstOrNull()
==
.firstOrNull { ... }
?: emptyList()
==
.orEmpty()
❤️ 1
v
@ephemient Sorry I didn't understand correctly, Can you please explain me, what will go inside first
filter
and you comparing
==
so what will be come there and how it will
sort
my list as well?
d
Copy code
filteredTopics.value = list.firstOrNull { it.topics != null && it.title == value.title }
You can simply "drop" filter
since firstOrNull will do the filtering
v
and ==
whatwillcomehere
.firstOrNull { ... }?
d
And ".orEmpty" that I didn't know about 😄 is nice sugar to use instead of ?:emptyList()
Copy code
filteredTopics.value = list.firstOrNull { it.topics != null && it.title == value.title }".orEmpty()" <<< THIS IS WRONG! should be like ephemient mentioned bellow:
filteredTopics.value = list.firstOrNull { it.topics != null && it.title == value.title }?.topics?.sortedBy { it.title }.orEmpty()
This, you should be able to use just that instead
v
Okk I'll try that.
Thank you so much
d
I learnt something new as well!
e
the == have equivalent results. to match the original snippet, it would look like
Copy code
filteredTopics.value = list.firstOrNull { it.topics != null && it.title == value.title }?.topics?.sortedBy { it.title }.orEmpty()
v
nice @ephemient thank you so much. It really help me.
Thank you once again @Diego Marzo
p
Why is that stateflow wrapped in a lazy?
v
for lazy initialized, Is there any problem in that?
p
Why do you do that?
If there is not more to it, it's just another additional allocation of the lazy and only makes the code a little bit more complex
e
lazy has cost: additional boxing, lambda creation, reflection data, synchronization, …
Chet and Romain go into this:

https://youtu.be/ULgEn3-pzzs?t=932

v
Okk I'll remove that.