[Idea] Suspending function support
a11n opened this issue · comments
Result
currently does not support suspending functions.
The following example won't compile:
suspend fun aSuspendingFunction() : Something
val result = Result.of { aSuspendingFunction() } //-> "Suspension functions can be called only within coroutine body"
Since Result
is nice, for instance to work with web service calls, it would be very cool to support this new Kotlin feature right out of the box.
I'm currently using this workaround to work with Result
in conjunction with coroutines:
val result = resultOf { aSuspendingFunction() }
private suspend fun <V : Any> resultOf(f: suspend () -> V): Result<V, Exception> = try {
Success(f())
} catch (e: Exception){
Failure(e)
}
What do you think? If you like the idea I could prepare an according PR.
Result.success()
, Result.failure()
and Result.fold()
are also not capable of suspending functions at the moment.
Currently working around with:
suspend fun <V : Any> Result<V, *>.successSuspend(f: suspend (V) -> Unit) {
when(this){
is Success -> f(this.value)
else -> {}
}
I support the idea very much! 👍 👍
With the version 1.4.0, this issue should be closed as fixed :)