简体   繁体   中英

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM