https://kotlinlang.org logo
Title
t

therealbluepandabear

05/13/2022, 8:19 AM
var toReturn: PixelArt? = null

    CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
        AppData.pixelArtDB.pixelArtCreationsDao().getAllPixelArtCreations().observe(this@extendedGetCurrentPixelArtObj.findViewTreeLifecycleOwner()!!) {
            toReturn = it[currentIndex]
        }
    }

    return toReturn!!
b

bezrukov

05/13/2022, 8:35 AM
One way would be to convert your livedata to flow, it should be available in some livedata-ktx androidx artifact https://developer.android.com/reference/kotlin/androidx/lifecycle/package-summary#(androidx.lifecycle.LiveData).asFlow() then you need to use
dao.liveDataQuery().asFlow().first()
BUT, you use Room, which natively supports coroutines, so you can simply switch from
LiveData
to
Flow
, or to simply
suspend
function
1
t

therealbluepandabear

05/13/2022, 8:44 AM
Thank u g, appreciated
m

Marcello Galhardo

05/13/2022, 8:55 AM
I believe Room supports
Flow
. There is no need to return a
LiveData
simple to convert it to a
Flow
. Google has a CodeLab that teaches you how to use Room and Flow. Check Respond to data changes using Flow.
t

therealbluepandabear

05/13/2022, 12:28 PM
amazing , thank u, didn't know this!
a

Adam Powell

05/13/2022, 1:46 PM
When using room you should prefer declaring a separate suspend DAO function instead of using .first on a flow from it. The flow sets up database change observers that are wastefully discarded immediately when you use .first with them
👍 2