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)
}
}
CodePudding user response:
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)
}
}