Sometimes I find a need for `withScope` instead of...
# coroutines
d
Sometimes I find a need for
withScope
instead of
withContext
. Now you have to write
withContext(myScope.coroutineContext)
but, given the intended purpose 😉 of
CoroutineScope
, I feel there should be a scope variant of it.
d
is it not what coroutineScope {} does?
d
You cant pass an explicit scope to that
I feel one potential issue which is that you cant really have 2 parents, when ideally,
withScope
can give you 2 parents. I assume
withContext
makes the paraneter's Job take precedence. Just entertaining some thoughts.
e
What would be your use-case for two parents?
d
That's a good question. I think the reason is that you have to drop one relationship when you want to change to another
CoroutineScope
. Maybe that's how it should be, and maybe that's why it's good that
withScope
doesn't exist.
e
But what is the use-case? Where it comes up?
d
I have an application where I'm rendering using OpenGL. The application is slowed down significantly by a particular aspect of it because it can make around 2 million queries to the memory of a particular process per frame. Hitting 20ms of frame time is not ideal. All of that work could be done on another thread, as it's just creating vertices in a buffer. That job should ideally be dependent on both scopes being alive; the main scope and the one I want to add.
e
What’s your main scope and which one you want to add?
d
My main scope is the one with the opengl context, it wraps an event loop. The new one would be on the default dispatcher.
I think a good solution to that would be to cancel the new scope when the main scope dies
Anyway, I'm just giving the idea of multiple parents a thought, I'm not necessarily advocating for it. I think it would bring many problems with it that would ultimately make it a bad idea.
What I end up doing each loop in the second thread, at the end is this:
Copy code
MainScope.launch {
    vertexBuffer.sync() // upload to GPU
}.join() // ensure it's uploaded before next iteration
This is OK. But
withContext
like mechanism would be more elegant. That's all.