'Execute in a separate thread

I have a small application which is responsible for intercepting requests and responses. Forms them into a package and can save them to local storage. I'm using the Room library to save data locally.

My code (shown below) is working, but it has a small brake in the form of allowMainThreadQueries() when building. I know that this cannot be done and all all IO actions must be performed in a separate thread.

Can you tell me how I can do this in a separate thread?

PacketsLocalDataSource.kt

    class PacketsLocalDataSource(private val context: Context) {
    lateinit var db: PacketsDatabase
    lateinit var dao: PacketDao

    fun saveLocal(packet: Packet) {
        db = PacketsDatabase.getInstance(context)!!
        dao = db.packetDao()
        dao.add(packet)
    }
}


Solution 1:[1]

You can use Coroutines to do background work.

 class PacketsLocalDataSource(private val context: Context) {
    private val dao: PacketsDao by lazy{PacketsDatabase.getInstance(context).packetDao() }

    fun saveLocal(packet: Packet) {
        CoroutineScope(Dispatchers.IO).launch { 
           dao.add(packet)
        }
    }

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 Daniel Knauf