Skip to content

Commit b0897a4

Browse files
committed
Use Room's queryDispatcher over Dispatchers.IO in LimitOffsetPagingSource
Allows overriding the Dispatcher for Room's generated PagingSource implementation, which is useful in testing. RelNote: "The PagingSource implementation generated by room-paging now uses the queryExecutor passed through RoomDatabase.Builder, so it can be overridden, instead of Dispatchers.IO previously." Test: ./gradlew room:room-paging:test Change-Id: Iae2598b4c865904a295a1de1e6722bff14ed08cf
1 parent c7e2047 commit b0897a4

5 files changed

Lines changed: 52 additions & 14 deletions

File tree

‎room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/test/PagingSourceTest.kt‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ import org.junit.After
6969
import org.junit.Before
7070
import org.junit.Test
7171
import org.junit.runner.RunWith
72+
import java.util.concurrent.Executors
7273
import kotlin.test.assertFailsWith
7374
import kotlin.test.assertFalse
7475
import kotlin.test.assertTrue
@@ -83,7 +84,10 @@ class PagingSourceTest {
8384
private lateinit var coroutineScope: CoroutineScope
8485
private lateinit var db: Paging3Db
8586
private lateinit var itemStore: ItemStore
86-
private val queryExecutor = FilteringExecutor()
87+
88+
// Multiple threads are necessary to prevent deadlock, since Room will acquire a thread to
89+
// dispatch on, when using the query / transaction dispatchers.
90+
private val queryExecutor = FilteringExecutor(delegate = Executors.newFixedThreadPool(2))
8791
private val mainThreadQueries = mutableListOf<Pair<String, String>>()
8892
private val pagingSources = mutableListOf<PagingSource<Int, PagingEntity>>()
8993

‎room/room-ktx/src/main/java/androidx/room/CoroutinesRoom.kt‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public class CoroutinesRoom private constructor() {
6060
// Use the transaction dispatcher if we are on a transaction coroutine, otherwise
6161
// use the database dispatchers.
6262
val context = coroutineContext[TransactionElement]?.transactionDispatcher
63-
?: if (inTransaction) db.transactionDispatcher else db.queryDispatcher
63+
?: if (inTransaction) db.transactionDispatcher else db.getQueryDispatcher()
6464
return withContext(context) {
6565
callable.call()
6666
}
@@ -81,7 +81,7 @@ public class CoroutinesRoom private constructor() {
8181
// Use the transaction dispatcher if we are on a transaction coroutine, otherwise
8282
// use the database dispatchers.
8383
val context = coroutineContext[TransactionElement]?.transactionDispatcher
84-
?: if (inTransaction) db.transactionDispatcher else db.queryDispatcher
84+
?: if (inTransaction) db.transactionDispatcher else db.getQueryDispatcher()
8585
return suspendCancellableCoroutine<R> { continuation ->
8686
val job = GlobalScope.launch(context) {
8787
try {
@@ -117,7 +117,7 @@ public class CoroutinesRoom private constructor() {
117117
}
118118
observerChannel.trySend(Unit) // Initial signal to perform first query.
119119
val queryContext = coroutineContext[TransactionElement]?.transactionDispatcher
120-
?: if (inTransaction) db.transactionDispatcher else db.queryDispatcher
120+
?: if (inTransaction) db.transactionDispatcher else db.getQueryDispatcher()
121121
val resultChannel = Channel<R>()
122122
launch(queryContext) {
123123
db.invalidationTracker.addObserver(observer)
@@ -144,10 +144,12 @@ public class CoroutinesRoom private constructor() {
144144
*
145145
* @hide
146146
*/
147-
internal val RoomDatabase.queryDispatcher: CoroutineDispatcher
148-
get() = backingFieldMap.getOrPut("QueryDispatcher") {
147+
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
148+
public fun RoomDatabase.getQueryDispatcher(): CoroutineDispatcher {
149+
return backingFieldMap.getOrPut("QueryDispatcher") {
149150
queryExecutor.asCoroutineDispatcher()
150151
} as CoroutineDispatcher
152+
}
151153

152154
/**
153155
* Gets the transaction coroutine dispatcher.

‎room/room-paging/src/androidTest/kotlin/androidx/room/paging/LimitOffsetPagingSourceTest.kt‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,20 @@ import androidx.test.core.app.ApplicationProvider
3333
import androidx.test.ext.junit.runners.AndroidJUnit4
3434
import androidx.test.filters.SmallTest
3535
import androidx.testutils.FilteringExecutor
36+
import androidx.testutils.TestExecutor
3637
import com.google.common.truth.Truth.assertThat
38+
import kotlinx.coroutines.CoroutineScope
3739
import kotlinx.coroutines.Dispatchers
40+
import kotlinx.coroutines.launch
3841
import kotlinx.coroutines.runBlocking
3942
import org.junit.After
4043
import org.junit.Before
4144
import org.junit.Rule
4245
import org.junit.Test
4346
import org.junit.runner.RunWith
47+
import java.util.concurrent.Executors
4448
import java.util.concurrent.TimeUnit
49+
import kotlin.coroutines.EmptyCoroutineContext
4550
import kotlin.test.assertFailsWith
4651
import kotlin.test.assertFalse
4752
import kotlin.test.assertTrue
@@ -76,6 +81,30 @@ class LimitOffsetPagingSourceTest {
7681
assertThat(countingTaskExecutorRule.isIdle).isTrue()
7782
}
7883

84+
@Test
85+
fun load_usesQueryExecutor() {
86+
val queryExecutor = TestExecutor()
87+
database = Room.inMemoryDatabaseBuilder(
88+
ApplicationProvider.getApplicationContext(),
89+
LimitOffsetTestDb::class.java,
90+
).setQueryExecutor(queryExecutor)
91+
.setTransactionExecutor(queryExecutor)
92+
.build()
93+
94+
val job = CoroutineScope(EmptyCoroutineContext).launch {
95+
LimitOffsetPagingSourceImpl(database).load(
96+
PagingSource.LoadParams.Refresh(
97+
key = null,
98+
loadSize = 1,
99+
placeholdersEnabled = true
100+
)
101+
)
102+
}
103+
104+
queryExecutor.executeAll()
105+
assertThat(job.isCompleted)
106+
}
107+
79108
@Test
80109
fun test_itemCount() {
81110
dao.addAllItems(ITEMS_LIST)
@@ -744,7 +773,9 @@ class LimitOffsetPagingSourceTestWithFilteringExecutor {
744773

745774
private lateinit var db: LimitOffsetTestDb
746775
private lateinit var dao: TestItemDao
747-
private val queryExecutor = FilteringExecutor()
776+
// Multiple threads are necessary to prevent deadlock, since Room will acquire a thread to
777+
// dispatch on, when using the query / transaction dispatchers.
778+
private val queryExecutor = FilteringExecutor(delegate = Executors.newFixedThreadPool(2))
748779
private val mainThreadQueries = mutableListOf<Pair<String, String>>()
749780

750781
@Before

‎room/room-paging/src/main/kotlin/androidx/room/paging/LimitOffsetPagingSource.kt‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,14 @@ import androidx.annotation.NonNull
2121
import androidx.annotation.RestrictTo
2222
import androidx.paging.PagingSource
2323
import androidx.paging.PagingState
24-
import androidx.room.withTransaction
2524
import androidx.room.InvalidationTracker
2625
import androidx.room.RoomDatabase
2726
import androidx.room.RoomSQLiteQuery
27+
import androidx.room.getQueryDispatcher
2828
import androidx.room.util.CursorUtil
29+
import androidx.room.withTransaction
2930
import androidx.sqlite.db.SupportSQLiteQuery
30-
import kotlinx.coroutines.Dispatchers
3131
import kotlinx.coroutines.withContext
32-
import java.lang.IllegalArgumentException
3332
import java.util.concurrent.atomic.AtomicBoolean
3433
import java.util.concurrent.atomic.AtomicInteger
3534

@@ -70,7 +69,7 @@ abstract class LimitOffsetPagingSource<Value : Any>(
7069
private val registeredObserver: AtomicBoolean = AtomicBoolean(false)
7170

7271
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Value> {
73-
return withContext(Dispatchers.IO) {
72+
return withContext(db.getQueryDispatcher()) {
7473
registerObserverIfNecessary()
7574
val tempCount = itemCount.get()
7675
// if itemCount is < 0, then it is initial load

‎testutils/testutils-common/src/main/java/androidx/testutils/FilteringExecutor.kt‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,22 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
1919
import kotlinx.coroutines.flow.MutableStateFlow
2020
import kotlinx.coroutines.flow.first
2121
import kotlinx.coroutines.flow.mapLatest
22+
import kotlinx.coroutines.withTimeout
2223
import java.util.concurrent.Executor
24+
import java.util.concurrent.ExecutorService
2325
import java.util.concurrent.Executors
2426
import java.util.concurrent.TimeUnit
2527
import java.util.concurrent.locks.ReentrantLock
2628
import kotlin.concurrent.withLock
27-
import kotlinx.coroutines.withTimeout
2829

2930
/**
3031
* An executor that can block some known runnables. We use it to slow down database
3132
* invalidation events.
3233
*/
3334
@OptIn(ExperimentalCoroutinesApi::class)
34-
class FilteringExecutor : Executor {
35-
private val delegate = Executors.newSingleThreadExecutor()
35+
class FilteringExecutor(
36+
private val delegate: ExecutorService = Executors.newSingleThreadExecutor()
37+
) : Executor {
3638
private val deferred = mutableListOf<Runnable>()
3739
private val deferredSize = MutableStateFlow(0)
3840
private val lock = ReentrantLock()

0 commit comments

Comments
 (0)