API Calls Every X Seconds With Kotlin Flow in AndroidšŸš€

Debanshu Datta
Backyard Programmers
5 min readMar 7, 2022

--

Photo by Alexandra Gorn on Unsplash

In a recent Company Interview Assignment, I was given an interesting problem to make API calls every X second with the way to Pause and Play feature. Initially, I thought of using the WorkManger for this, but I later understood it has a minimum time limit of 15 minutes between scheduled times.

Disclaimer: It may not be a proper way but it worked really well for my use-case so here it is thanks.šŸ˜…

It was an interesting problem. During my research, I came across three prominent ways to one using RxJava, a second with Kotlin Flow and by using Kotlin Coroutine Timer.

In the below example, you can find how to do it with RxJava.

The second is using Kotlin Coroutine Timer, this is a great example with testable code.
https://github.com/Kotlin/kotlinx.coroutines/issues/1186#issuecomment-598473409

What is Kotlin Flow?

First of all, we have to understand Kotlin Flow

Flow is a stream that produces values asynchronously. Furthermore, Flow uses coroutines internally. And because of this, it enjoys all the perks of structured concurrency.

With structured concurrency, coroutines live for a limited amount of time. This time is connected to the CoroutineScope you start your coroutines in.

When you cancel the scope, you also release any running coroutines. The same rules apply to Kotlin Flow as well. When you cancel the scope, you also dispose of the Flow. You donā€™t have to free up memory manually!

Difference between channelFlow and Flow?āœØ

The main difference between channelFlowand the basic flowis described in the documentation:

A channel with the default buffer size is used. Use the buffer operator on the resulting flow to specify a user-defined value and to control what happens when data is produced faster than consumed, i.e. to control the back-pressure behavior.

Basic Poller ImplementationšŸŒˆ

Now that we have understood Kotlin Flow now it is time for some implementation.

Think of a scenario, where you have to fetch Cricket match status from an API and update the UI every 5 seconds. The user also has the option to Pause and Play these updating calls according to their need.

Letā€™s make a simple interface and we set the return type to Flow<T>, T is the Response that you are expecting with parameter, with delay for defining the delay between API calls and query for passing into the API calls.

We will implement the Poller Interface in DataPoller. We will be passing repository, viewModel, dispatcher. View Model provides us Network Availability and Polling State which is just a String, will help us to moniter 'ACTIVE' and 'INACTIVE' state, presnet in View Model. We are checking if the polling state is INACTIVE or Network not available then we are simply close() the Flow and return it from further execution. The while condition not isClosedForSend then after the base condition, we just add the delay() . Finally, we do the API calls through the repository inside the send() . One more thing worth mentioning is how to set the Dispatcher in the flowOn() which is passed inside the constructor.

isClosedForSend - Returns true if this channel was closed by an invocation of close. This means that calling send will result in an exception.
close()- Closes this channel. This is an idempotent operation ā€” subsequent invocations of this function have no effect and return false. Conceptually, it sends a special "close token" over this channel. Immediately after invocation of this function, isClosedForSend starts returning true.
send()- Sends the specified element to this channel, suspending the caller while the buffer of this channel is full or if it does not exist, or throws an exception if the channel is closed for send (see close for details).
flowOn()- Changes the context where this flow is executed to the given context. This operator is composable and affects only preceding operators that do not have its own context. This operator is context preserving: context does not leak into the downstream flow

Now your question will be how am I using it inside the project. This small snippet will give you some hints and a small example snippet.

Wow! You are done with setting up the Poller.šŸš€šŸŒˆ

For any doubts and suggestions, you can reach out on my Instagram, LinkedIn. Follow me for Kotlin content and more. Happy Coding!

I will well appreciate one of these šŸ‘

Recent Posts:

--

--

Debanshu Datta
Backyard Programmers

Android(L2) @Gojek | Mobile Developer | Backend Developer (Java/Kotlin)