Is there a difference between ``` launch(newSingl...
# coroutines
d
Is there a difference between
Copy code
launch(newSingleThreadContext("ServiceContext")) {
 ...
}
and
Copy code
launch {
 withContext((newSingleThreadContext("ServiceContext") {
    ....  
  }
}
?
m
Option #2 might do more work/thread switching, depending on CoroutineScope you're launching from
d
Yes and as far as I know the later is obsolet
b
Since you're creating a new thread context, #2 does indeed do an extra context switch which just causes extra overhead before your real work actually begins
That might not necessarily be the case if you did this though
Copy code
launch(start = UNDISPATCHED) { 
    withContext(newSingleThreadContext(...)) { 
        doSomething() 
    } 
}
e
There is no difference, but extra work and extra code in the second case. Use the first way when you need to launch in a specific context. Note, that that
newSingleThreadContex
is a resource that must be closed. Both your code example leak the newly created thread every time they launch a coroutine. Don’t do this. Do this:
Copy code
// at top level in some file
val myContext = newSingleThreadContex(...)

// somewhere in code
launch(myContext) { ... }
b
Is this thread context
Closable
that that it could be used via
newSingleThreadContext(...).use { launch(it) { ... } }
where it makes sense?
e
Yes