All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.youi.Blocked.scala Maven / Gradle / Ivy

The newest version!
package io.youi

import scala.concurrent.{Future, Promise}
import scribe.Execution.global

object Blocked {
  var enabled: Boolean = true

  private var map = Map.empty[Any, Future[_]]

  def apply[Result](keys: Any*)(f: => Future[Result]): Future[Result] = if (enabled) {
    synchronized {
      val previous = Future.sequence(keys.map(map.getOrElse(_, Future.successful(()))))
      val future = if (previous.isCompleted) {
        f
      } else {
        val promise = Promise[Result]
        previous.onComplete { _ =>
          val next: Future[Result] = f
          next.onComplete(promise.complete)
        }
        promise.future
      }

      keys.foreach { key =>
        map += key -> future
      }
      future
    }
  } else {
    f
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy