'Using coroutines to write to a log file without loosing the order the logs are in
I have created a custom logger to write all of my logs to file as well as to the android log. Since file writing is a blocking operation I now want to make the file-write asynchronous with Kotlin coroutines. Just wrapping the write in a coroutine doesn't work because then some logs get switched around and aren't written to file in the correct order. How can I make sure the logs are written sequentially while not blocking the main thread with file operations, optimally using Kotlin coroutines?
Solution 1:[1]
You can try to emit logs to MutableSharedFlow to write logs sequentially to a file:
class Logger {
// make sure `replay`(in case some logs were emitted before sharedFlow is being collected)
// and `extraBufferCapacity` is enough to handle all logs
private val sharedFlow = MutableSharedFlow<String>(replay = 64, extraBufferCapacity = 64)
private val scope = CoroutineScope(Dispatchers.IO)
init {
sharedFlow.onEach { log ->
println("$log")
// write to file here
TimeUnit.MILLISECONDS.sleep(100) // simulate writing to file
}.launchIn(scope)
}
fun log(message: String) {
sharedFlow.tryEmit(message)
}
}
fun test() {
val logger = Logger()
repeat(10) { item ->
logger.log("Log $item")
}
}
Need to be sure there are enough elements set to replay and extraBufferCapacity parameters of MutableSharedFlow to handle all logs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BigSt |
