arrow-fx / arrow.fx / IO / asyncF

asyncF

fun <A> asyncF(k: IOProcF<A>): IO<A>

Create an IO that executes an asynchronous process on evaluation. This combinator can be used to wrap callbacks or other similar impure code that require no cancellation code.

import arrow.core.*
import arrow.fx.*
import java.lang.RuntimeException

typealias Callback = (List<String>?, Throwable?) -> Unit

object GithubService {
  fun getUsernames(callback: Callback) {
    //execute operation and call callback at some point in future
  }
}

fun main(args: Array<String>) {
  //sampleStart
  fun getUsernames(): IO<List<String>> =
    IO.asyncF { cb: (Either<Throwable, List<String>>) -> Unit ->
      IO {
        GithubService.getUsernames { names, throwable ->
          when {
            names != null -> cb(Right(names))
            throwable != null -> cb(Left(throwable))
            else -> cb(Left(RuntimeException("Null result and no exception")))
          }
        }
      }
    }

  val result = getUsernames()
  //sampleEnd
  println(result.unsafeRunSync())
}

Parameters

k - a deferred asynchronous computation that might fail typed as IOProcF.

See Also

async

cancellableF

Do you like Arrow?

Arrow Org
<