Smart Text Listeners Using Flows on Android

Shivam Dhuria
Level Up Coding
Published in
2 min readNov 29, 2020

--

When you want to trigger a network request whenever the input text is edited, you will end up shooting a lot of requests for each letter added or removed.(eg Google search)

To solve this issue, you need to reduce the number of requests by waiting for some time until the user has finished typing a whole word. For Example, when the user is typing “Et”… “Eter”….. “Etern”….. “Eternal”. You intelligently only want to trigger a request when user has typed the whole word “Eternal”.

Setting up ViewModel

Set up a mock function that takes 1 sec to return a result when a query text is passed to it. Think of this function as a network request.

Now set up a _searchQuery and a setter function setSearchQuery() to set its value.

Attach a debouce() operator to the _searchQuery Flow. The debouce(1000) operator will filter out the values from the original _searchFlow and only emit values that have a delay of 1 second after they are emitted.

Now return the result of the longNetworkOperation() in map latest.

Setting up Activity/View

Add a text change listener to the EditText and call setSearchquery() in viewModel whenever the text is changed.

You can also collect the flows and print the result from the longNetworkOperation() we previously defined in the viewModel.

You can find the whole project at Github along with more use cases of using flows. Another similar article about using Using Flows Form Validation here.

--

--