Erik
04/24/2023, 12:31 PMwithContext(Dispatchers.Default) { Json./*... some (de)serialization function*/() }
, so that (de)serialization happens on a thread optimised for CPU-heavy work? Or is there built-in coroutine support in kotlinx.serialization, so that I can just call suspending versions of (de)serialiszation functions?CLOVIS
04/25/2023, 8:21 AMErik
04/25/2023, 12:05 PMCLOVIS
04/25/2023, 12:10 PMErik
04/25/2023, 12:13 PMIO
dispatcher on Android is optimised for IO work. The Main
dispatcher is not to be blocked. And then there's the Default
dispatcher for CPU work. And the coroutines lib smartly can switch between these dispatchers by (sometimes) not switching JVM threads underneath for efficiency.
So if I'm about to serialise something to post in a request, I think I could:Erik
04/25/2023, 12:14 PMval serialzedData = withContext(Dispatchers.Default) { Json.encodeToString(data) }
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { post(serializedData) }
CLOVIS
04/25/2023, 12:16 PMErik
04/25/2023, 12:17 PMErik
04/25/2023, 12:19 PMIO
and Default
dispatchers share underlying threads and do a best effort to prevent thread switchesErik
04/25/2023, 12:21 PMwithContext(Dispatchers.Default) {
val serialzedData = Json.encodeToString(data)
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { post(serializedData) }
}
To ensure that post
happens from within the IO dispatcher in the Default dispatcher, so that that optimisation kicks inErik
04/25/2023, 12:22 PMIO
should probably be encapsulated inside of the post
function, so that all these context switches are less visible and the code looks more streamlined)