A handy Kotlin coroutine extension for switching dispatcher

Imagine you have a suspend function like this:

1
2
3
suspend fun doSomething() = withContext(Dispatchers.IO) {
   // body
}

This looks alright. Using withContext every time looks a bit verbose though. There’s a nifty Kotlin extension on the invoke function that simplifies the code and makes it cleaner.

1
2
3
4
5
import kotlinx.coroutines.invoke

suspend fun doSomething() = Dispatchers.IO {
   // body
}

The invoke extension allows you to specify the dispatcher directly within the function call, eliminating the need for withContext.