API Calls Every X Seconds With Kotlin Flow in Android🚀
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.
Android Retrofit Call Every X Seconds - JournalDev
In this tutorial, we'll be implementing RxJava with Retrofit such that the Retrofit Service is called every x seconds…
The second is using Kotlin Coroutine Timer, this is a great example with testable code.
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
CoroutineScopeyou 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!
What is Flow in Kotlin and How to use it in Android Project?
If you are an Android developer and looking to build an app asynchronously you might be using RxJava as it has an…
Kotlin Flow for Android: Getting Started
In this tutorial, you'll learn about the basics of Kotlin Flow, and you'll build an Android app that fetches weather…
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.
Creates an instance of a cold Flow with elements that are sent to a SendChannel provided to the builder's block of code…
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.🚀🌈
I will well appreciate one of these 👏
Build Ktor Project with Docker and Add Nginx for Load Balancing & Reverse Proxy
We’ll see how to deploy a Ktor application to a Docker container, which can then be run either locally
Detect Swipe Direction on Jetpack Compose to trigger BottomSheetScaffold
The preceding chapter demonstrated how to detect some common types of gestures including dragging, tapping, and pinching…
Replacing Retrofit with Ktor Client and Kotlin Serialization for Android🐱🏍
Ktor includes a multiplatform asynchronous HTTP client, which allows you to make requests and handle responses, extend…
Making a Smartwatch Wear Face with Watch Face Studio⌚
Watch Face Studio is a graphical authoring tool that enables you to create watch faces for the Wear OS smartwatch…
Looking Into AsyncTask and WeakReference in Android💫
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the…