diego-gomez-olvera
09/20/2022, 3:47 PMprivate var currentJob: Job? = null
fun flushData() {
if (currentJob?.isActive == true) return
currentJob = scope.launch {
// Flush data while there is data to flush
}
}
The idea would be to avoid creating new unnecessary currentJob
having flushData
accessed potentially from any threaddiego-gomez-olvera
09/20/2022, 3:50 PMAtomic
types but that only works in JVM and Mutex.withLock
already requires to be launched from a Coroutine. The API is exposed to Android and iOS, so it seems best not to require the usage of Coroutines to call this methodCasey Brooks
09/20/2022, 3:55 PMChannel
, and then you can read from the Channel as a Flow to apply the skipping/restarting logic you need safely. Something like this might work
val flushDataChannel = Channel<Unit>(RENDEZVOUS, BufferOverflow.DROP_LATEST)
fun flushData() {
flushDataChannel.trySend(Unit) // returns ChannelResult.Failed if it's already processing a request
}
fun CoroutineScope.processFlushData() = launch {
flushDataChannel
.consumeAsFlow()
.onEach { /* Perform flush data operation */ }
.launchIn(this)
}
diego-gomez-olvera
09/20/2022, 3:57 PMChannel
with BufferOverflow.DROP_LATEST
can do the job, let me try. Thanks!Casey Brooks
09/20/2022, 3:59 PMdiego-gomez-olvera
09/20/2022, 4:04 PMprocessFlushData
?Casey Brooks
09/20/2022, 4:05 PMdiego-gomez-olvera
09/20/2022, 4:07 PMflushData
(called externally) and processFlushData
extensiondiego-gomez-olvera
09/20/2022, 4:08 PMCasey Brooks
09/20/2022, 4:11 PMprocessFlushData
is something you’d call once when the application starts up, so that it’s always ready to actually flush the data when you need to, but calling this method itself does not actually flush the data.
flushData
can be called from anywhere, on any thread, and it will simply request that the data be flushed by sending an object into the Channel. Only if processFlushData
is currently running in the background will the request actually be accepted and the data flusheddiego-gomez-olvera
09/20/2022, 4:14 PM