https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Remon Shehata

09/27/2023, 11:47 AM
Hey, I am trying to implement a search functionality that will hit the server endpoint. I am using
SharedFlow
,
collectLatest
and
debounce
so the endpoint won't be hit every time there is a text change. However,
collectLatest
is being called many times. why? and how can I fix it? full code
Copy code
searchText
                .debounce(1000)
                .distinctUntilChanged { prev, next -> prev != next }
                .filter { it.isNotEmpty() }
                .sample(500)
                .collectLatest {
                    Log.d("Remon", "search collect - value: $it")
                }
d

Damian Baczyński

09/27/2023, 12:43 PM
Are you sure that
distinctUntilChanged
has valid check? This lambda should check for elements equality and your current implementation does the opposite.
r

Remon Shehata

09/27/2023, 12:49 PM
I am not sure
I changed it so
prev == next
... same result..
d

Damian Baczyński

09/27/2023, 1:10 PM
I think this should be enough
Copy code
searchText
                .debounce(1000)
                .distinctUntilChanged()
                .filter { it.isNotEmpty() }
                .collectLatest {
                    Log.d("Remon", "search collect - value: $it")
                }
r

Remon Shehata

09/27/2023, 1:40 PM
still not working.. the collect block is called ~5 times
d

Damian Baczyński

09/27/2023, 1:47 PM
I checked this code and for me it seems to work. Can you give more context? How this flow is used? What is your expected behaviour?
r

Remon Shehata

09/27/2023, 1:48 PM
I found the issue, for me I was calling the whole block of code many times
thank you so much for your help
d

Damian Baczyński

09/27/2023, 1:49 PM
No problem K
🔥 1
❤️ 1