Kotlin Flow (part 1)

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.
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)
}
}
}
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))
}

