@@ -2,48 +2,37 @@ package com.powersync.integrations.room
22
33import androidx.room.RoomDatabase
44import androidx.room.Transactor
5+ import androidx.room.useReaderConnection
6+ import androidx.room.useWriterConnection
57import androidx.sqlite.SQLiteStatement
68import com.powersync.db.driver.SQLiteConnectionLease
79import com.powersync.db.driver.SQLiteConnectionPool
8- import kotlinx.coroutines.CompletableDeferred
9- import kotlinx.coroutines.CoroutineScope
10- import kotlinx.coroutines.coroutineScope
1110import kotlinx.coroutines.flow.MutableSharedFlow
1211import kotlinx.coroutines.flow.SharedFlow
13- import kotlinx.coroutines.launch
1412
1513public class RoomConnectionPool (
1614 private val db : RoomDatabase ,
17- private val scope : CoroutineScope ,
1815): SQLiteConnectionPool {
1916 private val _updates = MutableSharedFlow <Set <String >>()
2017
2118 override suspend fun <R > withAllConnections (action : suspend (SQLiteConnectionLease , List <SQLiteConnectionLease >) -> R ) {
2219 // We can't obtain a list of all connections on Room. That's fine though, we expect this to
2320 // be used with raw tables, and withAllConnections is only used to apply a PowerSync schema.
24- action(write(), emptyList())
25- }
26-
27- override suspend fun read (): SQLiteConnectionLease {
28- return obtainLease(true )
21+ write {
22+ action(it, emptyList())
23+ }
2924 }
3025
31- override suspend fun write (): SQLiteConnectionLease {
32- return obtainLease(false )
26+ override suspend fun <T > read (callback : suspend (SQLiteConnectionLease ) -> T ): T {
27+ return db.useReaderConnection {
28+ callback(RoomTransactionLease (it))
29+ }
3330 }
3431
35- private suspend fun obtainLease (readonly : Boolean ): SQLiteConnectionLease {
36- val obtainedLease = CompletableDeferred <SQLiteConnectionLease >()
37- scope.launch {
38- db.useConnection(readonly) { transactor ->
39- val completer = CompletableDeferred <Unit >()
40- obtainedLease.complete(RoomTransactionLease (transactor, completer))
41- completer.await()
42- }
32+ override suspend fun <T > write (callback : suspend (SQLiteConnectionLease ) -> T ): T {
33+ return db.useWriterConnection {
34+ callback(RoomTransactionLease (it))
4335 }
44-
45- val lease = obtainedLease.await()
46- return lease
4736 }
4837
4938 override val updates: SharedFlow <Set <String >>
@@ -56,7 +45,6 @@ public class RoomConnectionPool(
5645
5746private class RoomTransactionLease (
5847 private val transactor : Transactor ,
59- private val completer : CompletableDeferred <Unit >
6048): SQLiteConnectionLease {
6149 override suspend fun isInTransaction (): Boolean {
6250 return transactor.inTransaction()
@@ -68,8 +56,4 @@ private class RoomTransactionLease(
6856 ): R {
6957 return transactor.usePrepared(sql, block)
7058 }
71-
72- override suspend fun close () {
73- completer.complete(Unit )
74- }
7559}
0 commit comments