arrow-fx / arrow.fx / IO / cancellableF
fun <A> cancellableF(cb: ((Either<
Throwable
, A>) ->
Unit
) ->
IOOf
<
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.cancellableF { cb: (Either<Throwable, List<String>>) -> Unit ->
IO {
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())
}
cb
- a deferred asynchronous computation that might fail.
See Also
Do you like Arrow?
✖