SQLDelight in Android: Getting Started

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

Part 2: Advanced SQLDelight Integrations

13. Integrate with Kotlin Coroutines

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: 12. Integrate with RxJava Next episode: 14. Integrate with Android Paging

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: 13. Integrate with Kotlin Coroutines

The Kotlin Coroutines homepage provides more insight into what they are and how they work.

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 provides some extension points for other asynchronous programming models, which connect to its own Query API and the listener structure underneath it to create a better experience for developers.

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

    // Kotlin Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3"
}
-fun listCollections(): Query<Collection> {
+fun listCollections(): Flow<List<Collection>> {
    return database.collectionQueries.all()
}
fun listCollections(): Flow<List<Collection>> {
-    return database.collectionQueries.all()
+    return database.collectionQueries
+        .all()
+        .asFlow()
+        .mapToList()
}
-private val collectionQuery = repository.listCollections()
-
-private val collectionQueryListener = object : Query.Listener {
-    override fun queryResultsChanged() {
-        refreshState()
-    }
-}
init {
-    refreshState()
-
-    collectionQuery.addListener(collectionQueryListener)
+    viewModelScope.launch {
+      repository.listCollections()
+        .collect { collections ->
+
+        }
+    }
}
init {
    viewModelScope.launch {
      repository.listCollections()
        .collect { collections ->
+          _state.value = State.Result(
+            collections = collections
+          )
        }
    }
}
-override fun onCleared() {
-    collectionQuery.removeListener(collectionQueryListener)
-}
-
-private fun refreshState() {
-    _state.value = State.Result(
-        collections = collectionQuery.executeAsList()
-    )
-}