'Share a queue between the mainThread and a coroutine

I am new to the coroutine concept. I'm not very confident in the code I've written. Basically I have a queue of user events that I send to my server. Adding an event is done through the main thread and sends it into a coroutine. If the event was successfully sent, I delete it from the queue, if the send failed, it is not deleted and will be retried for the next cycle. To solve the concurrency issues I used a mutex. Can you tell me if pretty good or horrible and a solution in this case?

My code:

data class GeoDataEvent(
    val location : Location,
    val category : Int
)

// This class is instantiated in my android service
class GeoDataManager(private var mainRepository: MainRepository) {

    private var eventQueue : Queue<GeoDataEvent> = LinkedList()
    private val eventQueueMutex : Mutex = Mutex()

    fun enqueueEvent(location: Location, category : Int){
        CoroutineScope(Dispatchers.IO).launch {
            eventQueueMutex.withLock {
                eventQueue.add( 
                    GeoDataEvent(
                        location = location,
                        category = category
                    )
                )
            }
        }
    }

    // Called at each new location by Android location service
    private fun processNewLocation(location: Location){
         /* Some code */
        handleEventQueue()
    }

    
    private fun handleEventQueue(){
        CoroutineScope(Dispatchers.IO).launch {
            eventQueueMutex.withLock {
                if (eventQueue.isNotEmpty()) {
                    mainRepository.getAuthToken()?.let { token ->
                        eventQueue.peek()?.let { event ->
                           if (sendEvent(token, event)){
                             eventQueue.remove()
                           }
                        }
                    }
                }
            }
        }
    }

    private suspend fun sendEvent(token : String, event : GeoDataEvent) : Boolean {
        mainRepository.sendGeoDataEvent(token, event).let { res ->
            return res.isSuccessful
        }
    }
}
   

Thank you for your help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source