In Introduction to Multiplatform Persistence with SQLDelight it was mentioned that we still needed way to “manage observing of data updates (some interesting work being done on extension that supports Kotlin Coroutines Flow)”. Well, not long after that SQLDelight 1.1.4 was released with the aforementioned Flow support and this post gives short overview of exploration done to start using it.

Previously we had code like following in GalwayBusRepository (and continue to have so to support usage on iOS - more on that later). This would of course have only provided snapshot of what was in db at that time.

suspend fun getBusStops() = galwayBusQueries.selectAll(mapper = { stop_id, short_name, irish_short_name ->
        BusStop(stop_id.toInt(), short_name, irish_short_name)
    }).executeAsList()

With Flow support we can now add following (note asFlow() usage).

@ExperimentalCoroutinesApi
suspend fun getBusStopsFlow() = galwayBusQueries.selectAll(mapper = { stop_id, short_name, irish_short_name ->
        BusStop(stop_id.toInt(), short_name, irish_short_name)
    }).asFlow().mapToList()

This can then be invoked like following (using Flow’s collect() function) and code in lambda will get called each time db is updated.

repo.getBusStopsFlow().collect {
    // update UI
}

Regarding Kotlin Native support it looks like more work is still needed to support this (getting InvalidMutabilityException right now when I try to use this on iOS). See following for example - https://github.com/square/sqldelight/issues/1394 (I’ll post updates here when that situation changes)

Above code is available in the GalwayBus github repo.

Featured in Kotlin Weekly Issue #156