arrow-fx-coroutines / arrow.fx.coroutines / cancellable

cancellable

suspend fun <A> ~~cancellable~~(cb: ((Result<A>) -> Unit) -> CancelToken): A Deprecated: Use suspendCancellableCoroutine

Creates a cancellable suspend function 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.fx.coroutines.*
import java.lang.RuntimeException
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

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

class GithubId
object GithubService {
  private val listeners: MutableMap<GithubId, ScheduledFuture<*>> = mutableMapOf()
  fun getUsernames(callback: Callback): GithubId {
    val id = GithubId()
    val future = Executors.newScheduledThreadPool(1).run {
      schedule({
        callback(listOf("Arrow"), null)
        shutdown()
      }, 2, TimeUnit.SECONDS)
    }
    listeners[id] = future
    return id
  }
  fun unregisterCallback(id: GithubId): Unit {
    listeners[id]?.cancel(false)
    listeners.remove(id)
  }
}

suspend fun main(): Unit {
  //sampleStart
  suspend fun getUsernames(): List<String> =
    cancellable { cb: (Result<List<String>>) -> Unit ->
      val id = GithubService.getUsernames { names, throwable ->
        when {
          names != null -> cb(Result.success(names))
          throwable != null -> cb(Result.failure(throwable))
          else -> cb(Result.failure(RuntimeException("Null result and no exception")))
        }
      }
      CancelToken { GithubService.unregisterCallback(id) }
    }
  val result = getUsernames()
  //sampleEnd
  println(result)
}

Parameters

cb - an asynchronous computation that might fail.

See Also

suspendCoroutine

cancellableF

Do you like Arrow?

Arrow Org
<