SQLDelight in Android: Getting Started

Aug 3 2021 · Kotlin 1.4, Android 11, Android Studio 4.1

Part 2: Advanced SQLDelight Integrations

12. Integrate with RxJava

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Validate & Test Database Code Next episode: 13. Integrate with Kotlin Coroutines

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 12. Integrate with RxJava

To refresh your memory about RxJava, the project repository has more info on how it works.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

SQLDelight exposes a Query API to execute database functions on demand and allows users to attach listeners that get called whenever the underlying data has been updated. If you’re accustomed with the concepts of the reactive programming library RxJava, this may sound very familiar to you.

dependencies {
    implementation "com.squareup.sqldelight:rxjava3-extensions:$sqldelightVersion"

    // RxJava
    implementation "io.reactivex.rxjava3:rxjava:3.0.12"
}
-fun listCollections(): Query<Collection> {
+fun listCollections(): Observable<List<Collection>> {
    return database.collectionQueries.all()
}
fun listCollections(): Observable<List<Collection>> {
-    return database.collectionQueries.all()
+    return database.collectionQueries
+        .all()
+        .asObservable()
+        .mapToList()
}
-private val collectionQuery = repository.listCollections()
-
-private val collectionQueryListener = object : Query.Listener {
-    override fun queryResultsChanged() {
-        refreshState()
-    }
-}
+
+private var disposable = Disposable.empty()
init {
-    refreshState()
-
-    collectionQuery.addListener(collectionQueryListener)
+
+    disposable = repository.listCollections()
+      .subscribe { collections ->
+    
+    }
}
init {
    disposable = repository.listCollections()
        .subscribe { collections ->
+            _state.value = State.Result(
+                collections = collections
+            )
        }
    }
override fun onCleared() {
-    collectionQuery.removeListener(collectionQueryListener)
+    disposable.dispose()
}

-private fun refreshState() {
-    _state.value = State.Result(
-        collections = collectionQuery.executeAsList()
-    )
-}