raulraja
03/02/2019, 1:04 PMpakoito
03/02/2019, 10:46 PMpakoito
03/02/2019, 10:46 PMtakahirom
03/03/2019, 12:33 PMpackage test
import arrow.core.Either
import arrow.effects.ForIO
import arrow.effects.OnCancel
import arrow.effects.data.internal.BindingCancellationException
import arrow.effects.extensions.io.async.defer
import arrow.effects.extensions.io.fx.fxCancellable
import arrow.effects.fix
import arrow.effects.typeclasses.ConcurrentCancellableContinuation
import arrow.unsafe
import kotlinx.coroutines.*
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
fun main(args: Array<String>) {
val job = SupervisorJob()
val viewModel = ViewModel(job)
viewModel.loadSessions()
Thread.sleep(200L)
viewModel.loadSessions()
Thread.sleep(200L)
job.cancel()
Thread.sleep(200L)
/**
* output:
* Key note
* How to use Arrow Fx
*/
}
class ViewModel(private val job: Job) :
CoroutineScope by (CoroutineScope(job + Dispatchers.Default)) {
private val repository = Repository()
fun loadSessions() {
fxCancellable({
!effect {
repository.fetchSessions()
}
}, { either: Either<Throwable, List<String>> ->
either.fold({ throwable: Throwable ->
if (throwable !is BindingCancellationException) {
throwable.printStackTrace()
}
}, { list: List<String> ->
list.forEach(::println)
})
})
}
}
class Repository {
suspend fun fetchSessions(): List<String> {
delay(300L)
return listOf("Key note", "How to use Arrow Fx")
}
}
fun <A> CoroutineScope.fxCancellable(
arg0: suspend ConcurrentCancellableContinuation<ForIO, *>.() -> A,
onResult: (Either<Throwable, A>) -> Unit
) {
val (program, cancel) = fxCancellable(arg0)
val job: Job? = coroutineContext[Job]
job?.invokeOnCompletion {
cancel()
}
unsafe {
val coroutineDispatcher = coroutineContext[ContinuationInterceptor] ?: Dispatchers.Default as CoroutineContext
defer(coroutineDispatcher) { program }
.fix()
.unsafeRunAsyncCancellable(OnCancel.Silent, onResult)
}
}
raulraja
03/03/2019, 1:09 PMraulraja
03/03/2019, 1:10 PMraulraja
03/03/2019, 1:10 PMfxCancelable
blocks if you don;t want to use fibers https://arrow-kt.io/docs/effects/fx/async/#cancellationraulraja
03/03/2019, 1:12 PMraulraja
03/03/2019, 1:12 PMpakoito
03/03/2019, 3:17 PMtakahirom
03/04/2019, 1:34 PM