https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dennis Schröder

09/27/2019, 4:16 PM
Is there a difference between
Copy code
launch(newSingleThreadContext("ServiceContext")) {
 ...
}
and
Copy code
launch {
 withContext((newSingleThreadContext("ServiceContext") {
    ....  
  }
}
?
m

Marko Mitic

09/27/2019, 4:18 PM
Option #2 might do more work/thread switching, depending on CoroutineScope you're launching from
d

Dennis Schröder

09/27/2019, 4:19 PM
Yes and as far as I know the later is obsolet
b

bdawg.io

09/27/2019, 5:40 PM
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

elizarov

09/27/2019, 9:50 PM
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

bdawg.io

09/29/2019, 6:27 PM
Is this thread context
Closable
that that it could be used via
newSingleThreadContext(...).use { launch(it) { ... } }
where it makes sense?
e

elizarov

09/29/2019, 10:08 PM
Yes
8 Views