HiHowAreYou
HiHowAreYou

Reputation: 23

How to Adjust LiveData from Room Database Before It's Assigned to a Variable

I'm teaching myself Kotlin, based on some very old coding knowledge, so I might be missing something very obvious.

Basically, I want to adjust some LiveData slightly, every time it's returned from the Room database. The LiveData is a key value pair, and I want to make sure the key is assigned even if the requested item isn't in the database, so the LiveData is never null. I've tried a number of ways to do this -- most recently with a LiveData builder, but it tends to return null the first time, and then never updates. I think the problem I'm having (which I expected the LiveData builder to solve) is that the LiveData isn't returned from the database in time to make the adjustments.

I know I can do this with two LiveData objects -- observing the one that comes direct from the database, and then performing the adjustments before assigning it to a second variable -- but I'll be doing this with a large number of variables and there must be a cleaner way.

Here's the last thing I tried.

In ViewModel:

    val myLiveData = liveData {
        val rawLiveData = database.get("key")
        emit(myDataClass("key", rawLiveData.value?.plotInput.toString().trim()))
    }

In DAO

    @Query("SELECT * from database_table WHERE key = :key")
    fun get(key: String): LiveData<myDataClass?>

I hope this is clear, and not too dumb of a question!

Upvotes: 1

Views: 592

Answers (2)

Milad
Milad

Reputation: 977

Returning liveDate from a Room query is not the properly good way. LiveDate is a lifecycle component, it's better do not to use it in logic.

There are better alternatives like Flow. It is Reactive and more cleaner. Also, you can use Coroutines by just adding the suspend keyword to the method signature and returning the model class itself.

Upvotes: 3

Bink
Bink

Reputation: 2171

I believe the recommended way to do this is through Transformations—see https://developer.android.com/codelabs/kotlin-android-training-live-data-transformations#0 for details.

That said, LiveData appears to be on the way out (Android moves fast!) and you might want to consider using https://developer.android.com/kotlin/flow instead.

Upvotes: 1

Related Questions