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

louiscad

11/25/2018, 2:11 PM
Hi all, do you think such a class should be in kotlinx.coroutines?
Copy code
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

open class SuspendLazy<out T>(
    private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
    initializer: () -> T
) {
    private val lazyValue = lazy(initializer)
    suspend operator fun invoke(): T = with(lazyValue) {
        if (isInitialized()) value else withContext(dispatcher) { value }
    }
}
b

bdawg.io

11/25/2018, 8:38 PM
It seems like the initializer would need to be suspending to be very useful. Otherwise you might as well just do it directly
Copy code
lazy { withContext(dispatcher) { ... } }
You could also provide
fun <T> Lazy<T>.withDispatcher(dispatcher: CoroutineDispatcher) = DispatchingLazy(this, dispatcher)
to utilize all of the existing Lazy builders
l

louiscad

11/25/2018, 9:18 PM
The goal of this class is to have a lazy that is initialized on a specific dispatcher, and you access it with suspend function call syntax. It's not meant for lazy that needs suspend function to be called before it can be initialized, I haven't met such use case BTW.
b

bdawg.io

11/25/2018, 10:22 PM
I have met those use cases, but it would also require the
getValue
operator to support suspend too. All I was getting at is the ONLY part that is suspending is the context change using
withContext
. It currently seems to be just a Deferred represented in a Lazy interface
3 Views