Question: Is it safe to suspend unsafeRunSync
with IO
? E.g.
val io: IO[Unit] = //...
val io2: IO[Unit] = IO(io.unsafeRunSync)
The reason I would do so is that I have some class parameterized with F[_]: Effect
which is like a cache:
import cats.effect.Effect
final class MyChache[F[_]](implicit F: Effect[F]) {
private val cache = new ConcurrentHashMap[Int, String]
def getOrCreate(key: Int): F[String] = F delay {
cache.computeIfAbsent(
key,
k => longRunningEffecfulComputation(k).toIO.unsafeRunSync() // <-- Here
)
}
}
object MyCache {
def longRunningEffecfulComputation[F[_] : Effect](key: Int): F[String] = {
//...
}
}
The point is I want to run this long running effectfull computation only once for each key (it's pretty infrequent). Yet I would like to stay non-blocking when retrieving existing key.
ConcurrentHashMap
seems to be a perfect choice, but it requires this ugly trick with running and suspending the effect. Is there a better way to go?