arrow-fx / arrow.fx / IO / cancellable

cancellable

fun <A> cancellable(cb: ((Either<Throwable, A>) -> Unit) -> CancelToken<ForIO>): IO<A>

Creates a cancellable instance of IO that executes an asynchronous process on evaluation. This combinator can be used to wrap callbacks or other similar impure code that requires cancellation code.

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

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

class GithubId
object GithubService {
  private val listeners: MutableMap<GithubId, Callback> = mutableMapOf()
  fun getUsernames(callback: Callback): GithubId {
    val id = GithubId()
    listeners[id] = callback
    //execute operation and call callback at some point in future
    return id
  }

  fun unregisterCallback(id: GithubId): Unit {
    listeners.remove(id)
  }
}

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

      IO { GithubService.unregisterCallback(id) }
    }

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

Parameters

cb - an asynchronous computation that might fail.

See Also

async

Do you like Arrow?

Arrow Org
<