-
Notifications
You must be signed in to change notification settings - Fork 1.9k
async lazy val pattern causes infinite suspend #745
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Right.
Not really, for a couple of reasons. Firstly, it will make scoping rules non-trivial. Instead of "All coroutines launched from the scope are part of this scope" it will be "If ..., otherwise ...". Mental model with a lot of corner cases are proven to be less understandable and more error-prone, and we definitely don't want that. Secondly, there will be data race by design between the first call to
Depends on what you want. Both |
Thanks for your response. Actually the problem is simple, we have some kind of "View" object which has many properties those are interdependent example:
Problem is that rawLogs is expensive operation and I don't want to call it unless it's needed, also I want to cache a value and run fetch only once per "View" object. It's like some kind of lazy report which evaluates when accessing object's property. |
Core library should include fun getLog() = coroutineScope {
val logs by async(start = LAZY) { TODO() } // <-- GlobalScope?
...
} |
As I've mention previously, both |
When using |
My current code is the following, does it look right to you? private class SuspendLazySuspendingImpl<out T>(
private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
initializer: suspend () -> T
) {
private val lazyValue = lazy { GlobalScope.async(dispatcher) { initializer() }}
suspend operator fun invoke(): T = with(lazyValue) {
if (isInitialized()) value else withContext(dispatcher) { value }
}.await()
} |
Not sure why this is closed, this shouldn't break randomly depending on how you write the async. This suspends forever:
This works fine:
There should not be magic like this - esp considering this has been a problem for nearly two years. |
Hi, @chrisjenx, You can consider #1065 |
Hi,
I've just noticed that using new structural coroutines, the code which uses async(start = CoroutineStart.LAZY) { } causes infinite suspend.
As I understand these async(start = CoroutineStart.LAZY) is now treated as a children of TestView object and new coroutine engine waits until these async completes. Shouldn't LAZY async coroutines be excluded from a wait list if they are not running?
Maybe there are more proper way to implement lazy async val?
test example:
The text was updated successfully, but these errors were encountered: