Last active
February 2, 2020 16:30
-
-
Save taig/b64f95d67a8c10cf865925a0a176f670 to your computer and use it in GitHub Desktop.
Scala.js image loading with cats Deferred
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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