I use an EditText textField with TextWatcher attached. All of the callback methods fire events on every character I enter. In my case I call an api on text changed, to put the response into a label on the same fragment. I can not check the EditText for a certain format as it will be freetext.
Example: Whats your name?
E -> api call
R -> api call
I _> api call
K -> api call
How to avoid that? Can I use a timer (eg 2 seconds no text changed -> api call)? Maybe there is an elegant way of doing that.
If you are using Kotlin, you can do this with a coroutine. For example, if you want to run the API call 2 seconds after the text has stopped changing it would look like this:
In the Activity or Fragment with a ViewModel
In the ViewModel
Or without using a ViewModel
Using Jetpack Compose
The solution using Jetpack Compose is the same, just added to the
onValueChangelambda instead ofdoAfterTextChanged(either in place, or the same ViewModel call as before).Java Solution
If you are using Java, you could use a handler and a postDelayed runnable instead but the flow would be the same (on a text change, cancel the prior task and start a new one with a delay).