2

I have two tables, Location and Weather. They have one-to-one relationship. Weather has a foreign key that keeps the id of corresponding entry in Location.

@Entity(tableName = "location")
data class Location(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    ...
)

@Entity(
    tableName = "weather",
    foreignKeys = [
        ForeignKey(
            entity = Location::class,
            parentColumns = ["id"],
            childColumns = ["locationId"],
            onDelete = ForeignKey.CASCADE
        )
    ]
)
data class Weather(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    @ColumnInfo(name = "locationId") val locationId: Long,
    ...
)

Then I have this composite class:

data class LocationWeather(
    @Embedded val location: Location,
    @Relation(
        parentColumn = "id",
        entityColumn = "locationId"
    )
    val weather: Weather
)

I want to return a flow of list of LocationWeather so that when any of the tables are updated, I expect a new value to be emitted. Here is the DAO method:

@Transaction
@Query("SELECT * FROM location")
fun getLocationWeatherList(): Flow<List<LocationWeather>>

Then, I directly call DAO method in my ViewModel (just for now, there will be domain and data layers in between) to test it:

locationDao.getLocationWeatherList().onEach {
    // Only triggered once...
}.launchIn(viewModelScope)

However, I get data only once. There are no other emits after any of Location or Weather is updated, even though database inspector shows new entries.

I followed the official docs. The only difference is that, in the DAO method, instead of returning List<LocationWeather>, I return Flow<List<LocationWeather>>.

Is this expected or am I missing something?

Mehmed
  • 2,880
  • 4
  • 41
  • 62
  • You may find reading https://developer.android.com/kotlin/flow helpful. – MikeT May 28 '23 at 01:27
  • I can't spot any problems with the code you have posted. I would expect it to emit new items on each change. Possibly the problem is in code you haven't showed, like what you're doing in `onEach`. You say "show incoming data in the UI", which doesn't exactly make sense from a ViewModel. – Tenfour04 May 29 '23 at 17:55
  • I only have logging calls atm and `onEach` is not called after any update. Sorry for the misleading, removing that part of the comment from my question. – Mehmed May 30 '23 at 01:45
  • I am agonizing with the same, did you ever solve this, @Mehmed ? – Madis Männi Aug 02 '23 at 13:31
  • Nope. I just simplified my design by merging the two tables. Unfortunately, Android libs never surprises us by doing exactly what they are supposed to be doing. – Mehmed Aug 22 '23 at 17:46

0 Answers0