Is it possible to make a CoroutineContext.Element ...
# coroutines
e
Is it possible to make a CoroutineContext.Element that "falls off" in scopes that branch execution? For example:
Copy code
runBlocking(MyContext) {
  launch(<http://Dispatchers.IO|Dispatchers.IO>) {
   //doesn't contain my context anymore
  }
  launch {
   //still contains my context
  }
}
I need to be an identifier that indicates that a call is part of the same sequence of calls. Worst case even if I could just get it to log some kind of warning that would be a good start.
z
Not clear on what you’re actually asking – why should the second launch preserve it but not the first one? How is the first one not part of the “same sequence of calls” if the second one is? That said, if what you’re asking is possible, it’s probably going to be hacky, because that’s the opposite of the default behavior of contexts. So even if you can get that to work, it’s probably going to be brittle and really fun to maintain.
d
the first launch is providing a context as the argument. this creates a new context -- which inherits from MyContext but is no longer the same object
You should be able to add a custom Context key which would still be preserved in both cases, or .. something much simplier -- a local variable within runBlocking
e
Well the reason the second one would preserve it is because it's using the same Dispatcher so if I call this whole thing from runBlocking or a similar single threaded dispatcher I know that if a call comes in and it contains my custom context I know it was a recursive call basically. eg:
Copy code
val context = CustomContext()
suspend fun makeCall(callback: suspend () -> (Unit)) {
  if (currentCoroutineContext()[CustomContext] != null)
    //callback directly or indirectly recursively called makeCall
  else withContext(context) { callback() }
}
however if execution branches this still detects the recursive call (as it should) even if it's at a later time (which is helpful in some cases but in my case I would like to handle that differently)