Android Generic function for Flow in State Management

Teo
3 min readSep 14, 2021

As mobile developer, state management is always a hot topic to maintain different states such as Success , Failure , Loading , Retry , etc. Kotlin offers a convenient way to handle these states by using Sealed Class .

Sealed Class

Let’s take a example, gist below showed a wrapper for API responses. Generally, when we called an API to fetch data, there will be 3 main type of states which are Success , Error and Loading . Hence, we created a sealed class to wrap all these states together. (Note: Success have a generic type of R which allows generics datatype as its input)

MVVM Architecture + Flow

As in Android, MVVM is the official recommended architecture and all the network call should be done in Repository , and further bring up the state + data to ViewModel as well as View . Besides, we also used Flow to emit stream of data asynchronously from the API response.

Here is an example on Flow implementation combined with our Sealed class.

Generally, before calling any API, flow will emit Loading state and inform the UI now is “loading”, followed by sending API request. After API returns response, flow will emit Success if request is successful or emit Error if request is failed.

It seems to be readable and clean right? Imagine that you have multiple of API calls, Repository will be filled with all these boilerplate code!.

Here comes rescue. Generic function!

Since apiCall() is a suspend function, how can we create a generic function that accept suspend function as a parameter?

The answer is… lambda function! In gist below, toResultFlow() accept a suspend function parameter call with () (nothing) as input and Response<T>? as output. Then, in toResultFlow() , we will emit whatever state that we want just like the normal flow function we had written in the previous flow.

Then we can implement toResultFlow() in our repository easily without having to handle state manually every time in every function!

I had created an example that get upcoming movies list from TmDB API to showcase a solid example on how to implementing this generic toResultFlow() function.

Here is 3 gist that showcase Repository, ViewModel and View to wire up the whole flow.

The result will be like this.

Hope my article helps someone out there 😃. If I make any mistake please leave a comment. I am still continue to learn and willing to discuss any Android issue that faced. Cheers 🍷

Github: https://github.com/WenLonG12345/GenericFlowMVVM

--

--

Teo

React & Android Dev, JS & Kotlin Lover, Looking to do more and change the world! 🚀