louiscad
11/25/2018, 2:11 PMimport 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 }
}
}
bdawg.io
11/25/2018, 8:38 PMlazy { withContext(dispatcher) { ... } }
fun <T> Lazy<T>.withDispatcher(dispatcher: CoroutineDispatcher) = DispatchingLazy(this, dispatcher)
to utilize all of the existing Lazy builderslouiscad
11/25/2018, 9:18 PMbdawg.io
11/25/2018, 10:22 PMgetValue
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