2

I'm trying to create lazy function my coroutines. I created util function like this.

fun <T> lazyCoroutine(scope: CoroutineScope, block: suspend CoroutineScope.() -> T): Lazy<T> {

    val some = scope.async(start = CoroutineStart.LAZY) {
        block.invoke(this)
    }
    return lazy {
        some.await()
    }
}

But in the terminal show

my error

I'm also don't want to return Deferred<T> , I only want to return just out come of deferred. I saw most of the article return Deferred<T> which is not suitable with my scenario. Is there any relevant solution please point me out. Have a great day!.

myscenario

amlwin
  • 4,059
  • 2
  • 15
  • 34

1 Answers1

6

I saw most of the article return Deferred<T> which is not suitable with my scenario.

You have not made it clear what exactly is not appropriate about Deferred, but if it's the very fact that await() is a suspendable function, then you seem to ask for self-contradictory results: you want the user to call a non-suspendable function, but the implementation to use a suspendable one, and you expect the overall result to be non-blocking. No amount of wrapping or adapting will allow you to avoid blocking from outside the suspendable domain.

If you want to stay with a plain, non-suspendable function, then don't use coroutines at all, they will be just another layer of complication and your thread will still block until the value is available.

If you are OK with a suspendable function, then you should embrace Deferred:

fun <T> CoroutineScope.lazyCoroutine(
        block: suspend CoroutineScope.() -> T
): Deferred<T> {
    return async(start = CoroutineStart.LAZY) { block() }
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436