2

i'm trying to fetch some data from api, and them store on room database, so the main data source is roomDatabase.

my repository code looks like:

 suspend fun fetchData(): Flow<Response<List<Foo>>> {
            val shouldRequestData = dao.getFoo().isEmpty()
            return if (shouldRequestData) {
                getFoo()
            } else getLocalFoo()
        }
    
        override suspend fun getFoo(): Flow<Response<List<Foo>>> {
    
            return ....... request done normally... inserting normally on database (and showing 
on database inspector)
        }
    
        override suspend fun getLocalFoo(): Flow<Response<List<Foo>>> = flow {
            dao.getFoo().transform<List<FooLocal>, Response<List<Foo>>> {
               Response.Success(
                   it.map {
                     it.toDomainModel()
                   }
               )
    }
}

on Dao:

 @Query("SELECT * FROM localdb")
    fun getFoo(): Flow<List<Foo>>

and then collecting it normally on viewmodel...

The problem is: the data is not appearing.. how could i solve this? The non-flow version works :/ I already searched for this problem, but nothing seems to work.

Sx67
  • 53
  • 5

2 Answers2

0

Solved by putting this on getLocalFoo() ->

val result: Flow<Response<List<Foo>>> = 
     Transformations.map(dao.getFoo()) {
            Response.Success(it?.map {
                it.asDomainModel()
            } ?: emptyList()
        }.asFlow()

return result
Sx67
  • 53
  • 5
0

I have found a solution to investing so much time.

Solution: Same Dao Object should be used when we insert details into the room database and get information from DB.

If you are using dagger hilt then

@Singleton annotation will work.

I hope this will solve your problem.