https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Marharyta Nedzelska

05/03/2018, 7:41 AM
Is there any way to convert guava ListenableFuture into Kotlin Deferred? I see that there is an extension method await on ListenableFuture in kotlin-coroutines-guava but it is not what I need
d

diesieben07

05/03/2018, 7:43 AM
Copy code
val deferred = async { future.await() }
👍 2
v

Vsevolod Tolstopyatov [JB]

05/03/2018, 8:30 AM
also, you can use LF’s callback:
Copy code
fun <T> ListenableFuture<T>.toDeferred(): Deferred<T?>  {
        val deferred = CompletableDeferred<T?>()
        Futures.addCallback(this, object : FutureCallback<T> {
            override fun onSuccess(result: T?) {
                deferred.complete(result)
            }

            override fun onFailure(t: Throwable?) {
                deferred.completeExceptionally(t!!)
            }
        } )
        return deferred
    }
to avoid unnecessary launch (~context switch)
m

Marharyta Nedzelska

05/03/2018, 10:45 AM
thank you
9 Views