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

turastory

08/14/2020, 1:49 AM
Are there any plans for supporting
suspend operator
soon or later? I’d like to do something like this:
Copy code
suspend inline operator fun <T> SuspendableLazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T
    = ...

private val value by suspendableLazy { getValue() }

fun test() = println(value)

private suspend fun getValue() { ... }
o

octylFractal

08/14/2020, 1:50 AM
I doubt this would ever be supported, because there's no scope to run the
value
in here if you want this, get an appropriate CoroutineScope and do
private val value = scope.async(start = CoroutineStart.LAZY) { getValue() }
👌 1
😭 1
t

turastory

08/14/2020, 2:11 AM
It’s my mistake that there’s no scope for running
value
🙏 But we can handle that by implementing SuspendLazy<T> like this:
Copy code
class SuspendableLazy<T>(scope: CoroutineScope, block: suspend () -> Unit) {
    suspend fun get(): T = scope.async { block() }.await()
}

suspend inline operator fun getValue(...) = await()

private val value by suspendableLazy(scope) { getValue() }
o

octylFractal

08/14/2020, 2:12 AM
the trick now is that
value
needs to be some sort of
private suspend val
as well, but that's not something that really exists yet. I don't know if it ever will, either it still wouldn't help with your use case of using it in a non-suspend function
(side note -- there actually is a single
suspend val
, it's
coroutineContext
, but that's a special intrinsic value, not a real feature)
t

turastory

08/14/2020, 2:22 AM
Thanks for reply! It helped me a lot 😃 I will be waiting to see if they put such kinds of
suspendable property
or not. (By the way, my first code snippet is incorrect! - I didn’t mean to use
value
in non-suspend function)
11 Views