Search code examples
kotlinkotlinx.coroutines

Convey intended thread type (IO, default, main) when declaring suspend function


When designing an API with a suspend function, sometimes I want to convey that this function should be called on, say, an IO thread. Other times that it is essential to do so.

Often it seems obvious; for example a database call should be called using Dispatchers.IO but if it's an interface function, then the caller cannot assume this.

What is the best approach here?


Solution

  • If the suspend function really must run in a specific context, then declare it directly in the function body.

    suspend fun doInIO() = withContext(Dispatchers.IO) {
    
    }
    

    If the caller should be able to change the dispatcher, the function can add the dispatcher as a default parameter.

    suspend fun doInIO(context: CoroutineContext = Dispatchers.IO) = withContext(context) {
    
    }