Suspending version of `lazy { ... }`
See original GitHub issueRight now, I implement this with:
class LazyValue<T>(private val inner: suspend () -> T) {
private val latch = Channel(Channel.RENDEZVOUS)
private val cond = AtomicBoolean()
private var value = null
suspend fun get(): T {
if (this.cond.compareAndSet(false, true)) {
this.value = this.inner()
this.latch.close()
} else {
this.latch.receiveOrNull()
}
return this.value
}
}
Although this kind of primitive seems reasonable enough to add by default.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:25 (11 by maintainers)
Top Results From Across the Web
Is it possible to suspendCoroutine in a "by lazy" initializer? I ...
In your suspend fun cameraCaptureSession() = suspendCoroutine... example, it looks like it would re-run the function each time it was called, ...
Read more >Composing suspending functions - Kotlin
LAZY ) is a replacement for the standard lazy function in cases when computation of the value involves suspending functions.
Read more >Lazy evaluated Coroutines in Kotlin | by Sampson Oliver
Today we'll show how to lazy-evaluate a piece of asynchronous work, so that we can ... fun <T> lazyPromise(block: suspend CoroutineScope.
Read more >Kotlin Coroutines: Composing Suspending Functions - YouTube
Kotlin Coroutines: Composing Suspending Functions - Sequential, Concurrent, and Lazy Execution. Watch later. Share. Copy link.
Read more >Once upon a time in Kotlin - ProAndroidDev
But lazy delegate cannot handle suspending functions: private val result: T by lazy { block() // should be called only from a coroutine...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Wow,
lazy
blocks a thread while waiting? Are you kidding me?? I thought Kotlin is all about coroutines.You can use
val lazyValue = GlobalScope.async(Dispatchers.Unconined, start = LAZY) { inner() }
And even provide your own dispatcher if you need one to offload the computation.I don’t think such shorthand worth its own primitive: we don’t have
suspend
getters and thus can’t haveby lazy
like API. But let’s keep this issue open and see whether we have a demand on suspendable lazy.