Skip to main content

Command Palette

Search for a command to run...

Kotlin Flow (part 1)

Updated
2 min readView as Markdown
Kotlin Flow (part 1)
O

I am a software engineer passionate about environmental sustainability, I want to leverage technology for positive global change. My journey has equipped me with a blend of skills and experiences that I am eager to bring to solving challenges through data-driven solutions.

💡
This one is on flows, emit() and collect()

Flow → is a corountine-based concept. The entirety of which provides a way of writing code that doesn’t block your app - asynchronous code.

Flow → comes in when working with data that comes in gradually, instead of at once. E.g. A user’s input.

Flow → gives you a way to handle multiple asynchronous outputs. Removing the bottleneck of using endless callbacks to handle outputs that change over time.


Data is emitted into a flow using the emit() function.

fun signIn(): Flow<Resource<Any>> = flow {

        val result = safeApiCall { apiService.signin() }

        if (result.isSuccess()){
            emit(Resource.success(result.message))
        } else{
            emit(Resource.error(result.message))
        }
    }

Wrapping your function around the flow builder without emitting any value (using emit()) doesn’t do anything with the flow.


The data is collected using a collect() function.

fun signIn(authRequest: AuthRequest) {
        viewModelScope.launch {
            impl.signIn(authRequest).collect { token ->
                Log.v("token", token.token)
            }
        }
    }
💡
Note: The code inside a flow doesn’t run until the flow is collected (.collect())

Question:

Why wrap an API call in a flow even though its data comes back at once and not gradually?

One easy answer, which is in the first example above:

With flow → I can expand one call to emit different states based on the result returned. Hence, I can achieve a centralised way of returning values.

        if (result.isSuccess()){
            emit(Resource.success(result.message))
        } else{
            emit(Resource.error(result.message))
        }

Kotlin Concepts

Part 1 of 1

In this series, I will explore Kotlin concepts and demonstrate them through practical app examples.