arrow-fx-coroutines / arrow.fx.coroutines / Promise

Promise

interface Promise<A>

When made, a Promise is empty. Until it is fulfilled, which can only happen once.

A Promise is commonly used to provide and receive a value from 2 different threads, since Promise can only be completed once unlike ConcurrentVar we can consider it a synchronization primitive.

Let’s say we wanted to await a Fiber, we could complete a Promise latch to signal it finished. Awaiting the latch Promise will now prevent main from finishing early.

import arrow.fx.coroutines.*

suspend fun main(): Unit {
  val await = Promise<Unit>()

  ForkConnected {
    println("Fiber starting up!")
    sleep(3.seconds)
    println("Fiber finished!")
    await.complete(Unit)
  }

  await.get() // Suspend until fiber finishes
}

Types

AlreadyFulfilled object AlreadyFulfilled

Functions

complete Completes, or fulfills, the promise with the specified value A. Returns Promise.AlreadyFulfilled in Either.Left if the promise is already fulfilled.abstract suspend fun complete(a: A): Either<AlreadyFulfilled, Unit>
get Get or throw the promised value, use attempt when throwing is not required. Suspends until the promised value is available.abstract suspend fun get(): A
tryGet Try get the promised value, it returns null if promise is not fulfilled yet. Returns A if promise is fulfilled.abstract suspend fun tryGet(): A?

Companion Object Functions

invoke suspend operator fun <A> invoke(): Promise<A>
unsafe fun <A> unsafe(): Promise<A>

Do you like Arrow?

Arrow Org
<