Hi, Is the `IO.unsafeRunSync()` so dangerous that...
# arrow
d
Hi, Is the
IO.unsafeRunSync()
so dangerous that it cannot be called in production code? I need to execute
IO
in the current thread and
unsafeRunSync
seems reasonable in such case. Questions: 1. What can go wrong during the execution of
unsafeRunSync
? 2. How to execute
IO
in the current thread?
p
2 is not visible as an scheduler yet https://kotlinlang.slack.com/archives/C5UPMM0A0/p1586437549202900 1
.attempt().unsafeRunSync()
runs your program as returns an
Either
. It’s meant as an entry point. If you need to do
IO
inside something that’s not entry-programmy like an event callback, there’s a way of doing it through a
Promise
or a
Channel
.
Promise/Queue still require calling unsafeRunAsync to set a value. Still, they decouple your business logic from the event handler, and makes it easier to test.
instead of
Copy code
system.handleEvent {
  val bla = run(it).unsafeRunSync() // block thread
  continue(bla) // side-effect outside IO
}
you have
Copy code
IO.fx {
  continueOn(dispatchers().default()) // process on the background
  val next = queue.take().bind()
  val bla = run(it).bind()
  effect { continue(bla) }.bind()
}.unsafeRunAsync { } // immediately free the thread

system.handleEvent {
 queue.offer(it)
  .fork() // offer the value on the background
  .unsafeRunAsync { } // immediately free the thread
}
if instead of that you are at a place that supports suspension, then
myIO.attempt().suspended()
is better than
unsafeRunAsync()
☝️ 1