https://kotlinlang.org logo
#compose
Title
# compose
j

julioromano

02/05/2021, 4:37 PM
On the debouncing of text fields I have a
BasicTextField
whose
onValueChange
does two things: 1. Feeds `onValueChange`’s value back to the
BasicTextField
to display what the user has typed. 2. Triggers an HTTP search call to fetch updated data to be displayed. I’d like to debounce 2. but not 1. but: since the
onValueChange
is a single callback I see no “easy” way to do it. Were I to debounce the whole
onValueChange
callback, the user will notice a lag with the on screen feedback too. I believe this is a pretty common use case so I’m wondering if there’s a compose friendly pattern to handle this or if something ad-hoc must be concocted.
👍 1
z

Zach Klippenstein (he/him) [MOD]

02/05/2021, 5:01 PM
It is smelly to be doing any sort of HTTP stuff from your composables anyway. I would fire text change events to a view model of some sort, and then that model can debounce the events it receives (e.g. using rx/flow operators or something else).
4
j

julioromano

02/05/2021, 5:04 PM
Yeah that’s what I’m doing, the text change event is sent down to the business logic component which deals with state management and http calls (pure kotlin code, no android). But I thought this kind of debouncing should happen at the earliest possible in the “chain” which in this case is in the UI layer (though this is debatable of course).
s

Se7eN

02/05/2021, 5:26 PM
You can debounce wherever you like after setting the new value.
Copy code
onValueChange = {
    value = it
    debounce(value)
}
z

Zach Klippenstein (he/him) [MOD]

02/05/2021, 5:33 PM
I thought this kind of debouncing should happen at the earliest possible in the “chain” which in this case is in the UI layer (though this is debatable of course).
Why? You’ve described a very good reason why not to do this. Another reason is responsibility – if the same view model were used with different UI, the same debouncing logic would probably need to be applied. If that logic is in the UI layer like you propose, then you’d have to duplicate/rewrite it. It would also probably be a lot easier to unit test the debouncing logic if it’s in your view model.
j

julioromano

02/05/2021, 5:43 PM
Lol. It is cool that you managed to highlight a blatant contradiction in my own thinking (that I was too blind to notice while writing). Sometimes my mind likes to play these kind of tricks to itself. Result: I get stuck in a loop. Or perhaps... this is just the way I used to do it with the legacy View system: since
EditText
manages its own internal state I could always debounce it on the UI side using
afterTextCange
without affecting the text fed back to the UI.
👍 1
Thanks for the insight!
z

Zach Klippenstein (he/him) [MOD]

02/05/2021, 5:53 PM
Happens to me all the time 😅
5 Views