Search code examples
kotlinkotlin-coroutinesktor

Default dispatcher for a custom scope


I have a class (singleton) that regularly refreshes cache of Cms values, this is inside a Ktor API

My implementation looks something like this:

class CmsProviderImpl {
  private val scope = CoroutineScope(Job())

  init {
      // Launch a new coroutine for refresh cache items
      scope.launch {
          while (isActive) {
              delay(TimeUnit.SECONDS.toMillis(900))
              refreshCacheCmsItems()
          } 
      }
  }
}

I know Ktor uses Dispatcher.IO by default in its Scopes, but what about this case? Should I specify the Dispatcher explicitly or CoroutineScope is smart enough to know to use Dispatcher.IO as well?

Looking for the best approach to run these types of tasks in background.


Solution

  • You have created a CoroutineScope and are explicitly using it. No, of course there's no magic here that'll change it to Dispatchers.IO. However, you can change that manually by passing Dispatchers.IO to CoroutineScope() instead of a plain new Job.