Member-only story

Flow Power in Android: Keeping Your Data Flowing Smoothly (Even in the Background)

efe budak

--

I remember using async tasks, RxJava, simple Thread objects, and LiveData for concurrency in android projects. Then everything changed when the Fire Nation attacked.

Wait! It’s not that.

Everything changed when I started using kotlin more and more. There was this coroutine that was praised by pretty much everyone I see as an expert on the software development.

Of course, there was a new cool kid in the neighbourhood who is a good friend of the coroutine. Flow…

You’ll find 5 useful tips. Simple but critical… Here we go!

Not a member? Read from here.

1) Same but Different

You can handle exceptions in Flows using either a try-catch block or the catch extension function, which internally utilizes a try-catch block for exception handling.

Personally, I prefer to use the catch extension function but different scenarios may require different approaches.

// Using try-catch block
viewModelScope.launch {
try {
dataFlow.collect { data ->
// Process the data
}
} catch (e: Exception) {
// Handle the exception
Log.e("FlowException", "Error occurred: ${e.message}")
}
}

//…

--

--

efe budak
efe budak

No responses yet