Skip to content

Instantly share code, notes, and snippets.

@taig
Last active February 2, 2020 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taig/b64f95d67a8c10cf865925a0a176f670 to your computer and use it in GitHub Desktop.
Save taig/b64f95d67a8c10cf865925a0a176f670 to your computer and use it in GitHub Desktop.
Scala.js image loading with cats Deferred
import cats.effect.concurrent.Deferred
import cats.effect.implicits._
import cats.effect.{ConcurrentEffect, IO}
import cats.implicits._
import org.scalajs.dom.html.Image
import org.scalajs.dom.{document, Event}
def loadImage[F[_]](url: String)(implicit F: ConcurrentEffect[F]): F[Boolean] =
for {
promise <- Deferred[F, Boolean]
image <- F.delay(document.createElement("img").asInstanceOf[Image])
register = { (event: String, result: Boolean) =>
val listener = (_: Event) =>
promise.complete(result).runAsync(_ => IO.unit).unsafeRunSync()
F.delay(image.addEventListener(event, listener))
}
_ <- register("load", true)
_ <- register("error", false)
_ <- F.delay(image.src = url)
result <- promise.get
} yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment