Search code examples
multithreadingscalaconcurrencyscala-cats

Running IO on background thread in scala cats


def backGroundTask:IO[Unit]={
IO
{
//Time consuming task
}
}

How to execute this task eagerly on a background thread?


Solution

  • You can use ContextShift.evalOn:

    def backGroundTask = IO {
          Thread.currentThread()
    }
    
    val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
    
    val ec = ExecutionContext.fromExecutor(Executors.newCachedThreadPool()) //create other execution context
    
    println(backGroundTask.unsafeRunSync()) // will print Thread[main,5,main]
    println(contextShift.evalOn(ec)(backGroundTask).unsafeRunSync()) //will print Thread[pool-1-thread-1,5,main]