Hi Android developers! I want to share what I went through while moving a project from RxJava to Kotlin Coroutines. Step by step, we'll look at what each tool brings to asynchronous programming and the problems I ran into along the way.
Table of Contents
- Why Migrate?
- Asynchronous Work with RxJava
- Migration Basics
- Managing CoroutineScope and Dispatchers
- Coroutines in the ViewModel
- Custom Extension Functions: throttleFirst and collectFlow
- Error Handling
- Best Practices
- Resources
Why Migrate?
Asynchronous work is part of every modern mobile app. Network requests, database operations and user interactions all run in the background, and they have to be managed properly to keep the app smooth for the user. RxJava has been the go-to tool here for a long time, but its complexity and learning curve have pushed some developers to look elsewhere. Kotlin Coroutines fills that gap with a simpler, more readable model.
What RxJava gives you:
- Reactive programming: A flexible model for working with data streams.
- A wide range of operators: An operator for almost every scenario.
- Use beyond Android: It works outside Android too, which helps keep projects consistent.
What Coroutines give you:
- Simpler, more readable code
- Less boilerplate
- Native Kotlin support
With that in mind, moving to Kotlin Coroutines can help you end up with a codebase that's easier to maintain.
Asynchronous Work with RxJava
RxJava is powerful for managing async work, but it can also lead to complex, repetitive code. In my previous project, this is the structure I used for network requests with RxJava:
abstract class RxUseCase<Response, Params> {
abstract fun execute(params: Params?): Observable<Response>
fun run(observer: DisposableObserver<Response>, params: Params?) {
execute(params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(observer)
}
}
This class let me make network requests with the given parameters. The problem was that every use case needed the same threading setup, which meant duplicated code and harder maintenance. The more use cases a project has, the more you feel it.
Migration Basics
The first step is to replace the RxJava-based structure with Kotlin Coroutines. We start with a basic coroutine-based use case class:
abstract class CoroutineUseCase<Response, Params> {
abstract suspend fun execute(params: Params?): Response
suspend fun run(params: Params?): Response {
return execute(params)
}
}
The function is marked with suspend, so it can be called from a coroutine and the async flow becomes much simpler to manage.
Key Differences
- RxJava: Handles async work with
ObservableandDisposableObserver. - Coroutines: Uses
suspendfunctions and a coroutine scope, which is simpler and easier to read.
With this simple step we left RxJava's complexity behind and started moving toward cleaner, easier-to-follow code.
Managing CoroutineScope and Dispatchers
With Kotlin Coroutines you need to decide two things: how long a coroutine lives and which thread it runs on. That's what CoroutineScope and Dispatcher are for.
Using CoroutineScope
A CoroutineScope manages the lifecycle of the coroutines started in it. In a ViewModel, using viewModelScope means coroutines are cancelled automatically along with the ViewModel. This is what keeps you from leaking memory and wasting resources.
abstract class CoroutineRequestUseCase<Response, Params> {
abstract suspend fun execute(params: Params?): Response
fun run(
scope: CoroutineScope,
observer: CoroutineObserver<Response>,
params: Params?
) {
scope.launch {
try {
val response = withContext(Dispatchers.IO) {
execute(params)
}
withContext(Dispatchers.Main) {
observer.onSuccess(response)
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
observer.onError(e)
}
}
}
}
}
Using Dispatchers
- Dispatchers.IO: For IO-bound work such as network calls and disk access.
- Dispatchers.Main: For UI updates.
- withContext: Marks the block of code that should run on a specific dispatcher.
This way each piece of work runs on the right thread, which is good for performance.
Coroutines in the ViewModel
In Android's MVVM architecture, ViewModels hold the data and talk to the UI. Using viewModelScope to tie coroutines to the ViewModel's lifecycle is one of the best ways to manage them.
Updating the UseCase Class
Let's have the use case take a CoroutineScope parameter, so the coroutine's lifecycle follows the ViewModel:
class MyViewModel : ViewModel() {
private val useCase = MyUseCase()
fun performNetworkRequest(params: Params) {
useCase.run(
scope = viewModelScope,
observer = object : CoroutineObserver<Response> {
override fun onSuccess(response: Response) {
// Handle the result
}
override fun onError(e: Exception) {
// Handle the error
}
},
params = params
)
}
}
With this approach:
- Dispatchers: Network calls run on
Dispatchers.IO, UI updates onDispatchers.Main. - Scope management:
viewModelScopecancels coroutines automatically with the ViewModel, so nothing leaks. - Clean code: Since the coroutine's lifecycle is tied to the ViewModel's scope, the use case can focus on business logic.
Update (2026): Two things are worth keeping in mind with this example. First,
catch (e: Exception)also catches theCancellationExceptionthrown on cancellation. In this particular codewithContextthrowsCancellationExceptionagain inside a cancelled coroutine, soonErrorisn't called, but as a general rule you should rethrowCancellationExceptionrather than swallow it. Second,viewModelScopealready runs onDispatchers.Main.immediate, so thewithContext(Dispatchers.Main)on the result side isn't needed. The common approach today is to keep the use case as a plainsuspendfunction that picks its own dispatcher withwithContext, launch it from the ViewModel withviewModelScope.launch, and expose the result to the UI through aStateFlow. The first suggestion in item 5 under Best Practices points the same way. Keeping the dispatcher choice in the layer that does the work (the use case or repository) rather than in the ViewModel makes that function main-safe, so it can be called from anywhere.
Custom Extension Functions: throttleFirst and collectFlow
During the migration I wrote a few custom extension functions to deal with problems I kept running into. Their job is to make working with coroutines and Flow easier and cut down on repeated code.
The throttleFirst Operator
throttleFirst is a Flow operator that lets only the first of a burst of events through. It emits the first value that arrives in a time window (windowDurationMillis) and ignores the rest until the window closes. That makes it a good fit for events that repeat quickly, like button clicks.
fun <T> Flow<T>.throttleFirst(windowDurationMillis: Long): Flow<T> = channelFlow {
val mutex = Mutex()
var lastEmitTime = 0L
collect { value ->
val currentTime = System.currentTimeMillis()
mutex.withLock {
if (currentTime - lastEmitTime >= windowDurationMillis) {
lastEmitTime = currentTime
send(value)
}
}
}
}
Update (2026): This implementation works, but it can be simpler.
collectalready processes values one at a time, so theMutexandchannelFlowaren't needed; a plainflow {}is enough. Also,System.currentTimeMillis()can jump forwards or backwards when the device clock changes. A monotonic clock such asSystemClock.elapsedRealtime()is safer for measuring intervals:fun <T> Flow<T>.throttleFirst(windowDurationMillis: Long): Flow<T> = flow { var lastEmitTime: Long? = null collect { value -> val now = SystemClock.elapsedRealtime() val last = lastEmitTime if (last == null || now - last >= windowDurationMillis) { lastEmitTime = now emit(value) } } }
Example
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.eventFlow
.throttleFirst(1000)
.collectLatest { event ->
handleEvent(event)
}
}
}
Advantages
- Prevents event flooding: Only the first event in the window is handled, so rapid repeats (e.g. multiple button taps) are ignored.
- Better user experience: If the user taps a button several times in a row, you avoid side effects like a fragment or dialog opening more than once.
- Easy to use: Instead of tracking repeats by hand, you can prevent these UI issues with
throttleFirst.
Things to Watch Out For
- The delay affects UX: Too short or too long a throttle window can both feel wrong, so settling on a standard value such as 300L is a good idea.
- Using it with StateFlow: StateFlow updates constantly, so a careless throttle duration can cause problems.
Update (2026): Concretely, the StateFlow problem is this:
throttleFirstdrops the later values in a window and never brings them back. The last state emitted inside the window may never be shown, leaving the UI on a stale state. So usethrottleFirstfor one-off events such as clicks and navigation (SharedFlow/Channel). For state streams, either don't throttle at all or prefer operators that keep the latest value, such asdebounceorsample.
The collectFlow Operator
collectFlow is a custom extension function I wrote to collect Flows in a lifecycle-aware way. It collects every value the Flow emits, in order, and lets you apply operators (throttle, debounce, etc.) to the Flow first.
fun <T> LifecycleOwner.collectFlow(
flow: Flow<T>,
state: Lifecycle.State = Lifecycle.State.STARTED,
flowOperator: (Flow<T>) -> Flow<T> = { it },
collector: suspend (T) -> Unit
) {
val collectedFlow = flowOperator(flow)
lifecycleScope.launch {
repeatOnLifecycle(state) {
collectedFlow.collect { collector(it) }
}
}
}
Example
private fun observeFlow() {
viewModel.run {
collectFlow(
flow = formDataFlow,
collector = { formData ->
binding.formListView.submitFormData(formData, listOf(0, formData.size - 1))
}
)
collectFlow(
flow = navigateBackSharedFlow,
flowOperator = { it.throttleFirst(DEFAULT_THROTTLE_TIME) },
collector = { finish() }
)
}
}
Update (2026): When you use these extensions in a Fragment, pass
viewLifecycleOwneras theLifecycleOwnerinstead of the Fragment itself (viewLifecycleOwner.collectFlow(...)). Otherwise the old collectors keep running when the view is recreated, and the same Flow ends up being collected more than once.
The collectLatestFlow Operator
collectLatestFlow is another extension I wrote for lifecycle-aware collection. It collects the latest emitted value: when a new value arrives, the collector block still running for the previous value is cancelled. You can apply operators to the Flow here as well.
fun <T> LifecycleOwner.collectLatestFlow(
flow: Flow<T>,
state: Lifecycle.State = Lifecycle.State.STARTED,
flowOperator: (Flow<T>) -> Flow<T> = { it },
collector: suspend (T) -> Unit
) {
val collectedFlow = flowOperator(flow)
lifecycleScope.launch {
repeatOnLifecycle(state) {
collectedFlow.collectLatest { collector(it) }
}
}
}
Example
private fun observeFlow() {
viewModel.run {
collectLatestFlow(
flow = formDataFlow,
collector = { formData ->
binding.formListView.submitFormData(formData, listOf(0, formData.size - 1))
}
)
collectLatestFlow(
flow = navigateBackSharedFlow,
flowOperator = { it.throttleFirst(DEFAULT_THROTTLE_TIME) },
collector = { finish() }
)
}
}
Advantages
- Lifecycle awareness: Flows are only collected while the lifecycle is in the right state, so no work is wasted.
- Flexibility: The
flowOperatorparameter lets you apply extra operators to the Flow. - Less duplication: Lifecycle handling and Flow collection live in one function, so you don't repeat the same block in every Activity or Fragment.
Use Cases
- Button clicks: Handling clicks that fire in quick succession.
- Navigation events: Stopping the user from triggering the same navigation several times with fast taps.
- Form input: Stopping the user from triggering form actions several times with fast taps.
Error Handling
Handling errors properly in async code matters a lot for your app's reliability. Kotlin Coroutines offers centralized error handling through CoroutineExceptionHandler.
Using CoroutineExceptionHandler
CoroutineExceptionHandler lets you handle unexpected errors in coroutines from one place, so you don't have to write separate error handling for each coroutine.
Adding the Exception Handler to the UseCase Class
abstract class CoroutineRequestUseCase<Response, Params> {
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
// Central error handling
Log.e("CoroutineException", "Unhandled exception: ${throwable.localizedMessage}", throwable)
// A logging/crash reporting tool (Timber, Crashlytics, etc.) can be plugged in here
}
abstract suspend fun execute(params: Params?): Response
fun run(
scope: CoroutineScope,
observer: CoroutineObserver<Response>,
params: Params?
) {
scope.launch(exceptionHandler) {
try {
val response = withContext(Dispatchers.IO) {
execute(params)
}
withContext(Dispatchers.Main) {
observer.onSuccess(response)
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
observer.onError(e)
}
}
}
}
}
Update (2026):
CoroutineExceptionHandleronly handles uncaught exceptions, and only when it's installed on a root coroutine (alaunchstarted directly in the scope) or in the scope's context. A handler passed to a child coroutine has no effect, andasynchands its exception toawait()instead. By the time the handler runs the coroutine has already finished, so it's a last-resort place for logging and reporting, not a recovery mechanism. In the example above thetry/catchalready catches everyException, so only what slips past it reaches the handler (for example, an exception thrown from insideonError).
Why It Matters
- Central handling: Handling errors in one place means you don't need separate handling in every coroutine.
- Cleaner code: Keeping error handling in one place makes the code easier to read.
- Reliability: You can prevent unexpected crashes and pass errors on to the user or to your logs.
Best Practices
A few practices help keep coroutine code clean, maintainable and fast.
1. CoroutineScope Management
- Use viewModelScope: Tie coroutines to the ViewModel's lifecycle.
viewModelScopecancels them automatically when the ViewModel is cleared. - Don't create extra scopes: Reusing the scopes you already have instead of creating a new
CoroutineScopekeeps the code simpler and resource management easier.
2. Dispatchers
- Dispatchers.IO: Use it for network calls and IO work.
- Dispatchers.Main: Use it for UI updates.
- withContext: Use
withContextto mark code that needs to run on a specific dispatcher.
3. Error Handling
- CoroutineExceptionHandler: Use it to handle uncaught exceptions centrally.
- try-catch blocks: Catch the errors you expect and give the user meaningful feedback.
- Errors inside a Flow: If you're using Flow, handle errors in the stream with the
catchoperator.
4. Dependency Injection (DI)
- Use a DI tool: Inject dependencies such as CoroutineScope and dispatchers with a DI tool (for example Hilt or Dagger).
- Testability: With DI, you can swap dispatchers for the
TestDispatchers fromkotlinx-coroutines-testin tests, and replace other dependencies with mocks or stubs.
5. Clean Architecture
- Design use cases as suspend functions: Keep business logic clean and independent.
- Manage coroutines in the upper layers: Handle coroutine and dispatcher management in layers like the ViewModel so responsibilities stay clear.
6. Testing
- Coroutine test libraries: Test your coroutines with the
kotlinx-coroutines-testlibrary. - Mocks and stubs: Replace dependencies with mock objects to test different scenarios.
Conclusion
Kotlin Coroutines is a flexible async programming tool for modern Android development. Moving from RxJava, you get the simplicity and readability coroutines offer. With the right scope management, dispatcher usage and error handling, your code becomes cleaner, easier to maintain and easier to test.
In this post I walked through the problems I hit while moving from RxJava to Coroutines and how I solved them. Applying these approaches can help you get to a more modern, better-performing codebase. Every project and team is different, though, so adapt them to your own needs.
Happy coding!
Additional Notes and Tips
- Code review and refactoring:
- Refactor step by step during the migration.
- Review the code after each change to catch bugs early.
- Documentation and standards:
- Document how coroutines are used in the project.
- Agree on coding standards so the whole team follows the same approach.
- Performance monitoring:
- Keep an eye on coroutine performance to spot bottlenecks.
- Tune dispatcher usage and scope management where needed.
These steps should help with the problems you may run into while moving from RxJava to Kotlin Coroutines. Take them one at a time and you'll get the most out of coroutines.
Resources
Frequently asked questions
- Why migrate an Android project from RxJava to Kotlin Coroutines?
- Coroutines give you simpler, more readable code, less boilerplate and native Kotlin support. The subscribeOn/observeOn setup you repeat for every RxJava use case goes away, which makes the codebase easier to maintain.
- How do you avoid memory leaks when running coroutines in a ViewModel?
- Launch them in viewModelScope. It cancels its coroutines automatically when the ViewModel is cleared. Reusing the existing scopes instead of creating extra CoroutineScopes also keeps resource management simple.
- Which dispatcher should handle network calls and which UI updates?
- IO-bound work such as network calls and disk access belongs on Dispatchers.IO, UI updates on Dispatchers.Main. You switch between them with withContext.
- What does the throttleFirst Flow operator do?
- It emits the first value in a given time window and ignores the rest until the window closes. That stops a dialog or fragment from opening twice when the user taps a button quickly. Because it drops values, use it carefully on state streams such as StateFlow.