StragaSevera
03/02/2025, 8:05 PMsummaryFlow().take(100).collect { summary ->
fileWriter.write(Json.encodeToString(summary))
}
What is the correct way to do it? Should I use withContext inside of the lambda, or flowOn before it?Youssef Shoaib [MOD]
03/02/2025, 8:09 PMcollect call itself in withContextZach Klippenstein (he/him) [MOD]
03/02/2025, 8:54 PMflowOn will change the context in which everything upstream of the operator runs.
• Surrounding the collect call with withContext will change the context in which the collect body runs, and may change the context upstream (but flowOn would override that).
• Putting withContext inside the collect will only change the context that the actual write and encodeToString functions run in.Zach Klippenstein (he/him) [MOD]
03/02/2025, 8:57 PMsummaryFlow().take(100).collect { summary ->
// This is CPU-bound work, so don't switch to IO yet.
val encoded = Json.encodeToString(summary)
// This is the blocking IO call.
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
fileWriter.write(encoded)
}
}Zach Klippenstein (he/him) [MOD]
03/02/2025, 8:58 PMStragaSevera
03/02/2025, 10:41 PM