Pablo
06/07/2024, 11:20 AMCannot access database on the main thread since it may potentially lock the UI for a long period of time.
That meand I need to make the dao insert function suspend and call it from a coruitine. Then why documentation says that rooms do that job automatically? why the codelabs show you all the daos without suspend? should I put suspend in every dao function then? I'm confussedStylianos Gakis
06/07/2024, 11:42 AMPablo
06/07/2024, 11:51 AM@Dao
interface FlightsDao {
@Query("SELECT * FROM airport ORDER BY passengers DESC")
fun getAllAirports(): Flow<List<Airport>>
@Query("SELECT * FROM airport WHERE iata_code LIKE '%'||:text||'%' OR name LIKE '%'||:text||'%' ORDER BY passengers DESC")
fun getAirportsByIatOrName(text: String): Flow<List<Airport>>
@Query("SELECT * FROM airport WHERE id NOT LIKE :id ORDER BY passengers DESC")
fun getAllDifferentAirports(id: Int): Flow<List<Airport>>
@Query("SELECT * FROM favorite")
fun getFavorites(): Flow<List<Favorite>>
@Query("SELECT EXISTS(SELECT * FROM favorite WHERE departure_code = :departureCode AND destination_code = :destinationCode)")
fun checkIfFavoriteExists(departureCode: String, destinationCode: String): Boolean
@Insert
fun insertFavorite(favorite: Favorite)
}
Pablo
06/07/2024, 11:51 AMPablo
06/07/2024, 11:53 AMPablo
06/07/2024, 11:53 AMPablichjenkov
06/07/2024, 1:13 PMsuspend
, you are doing an io
operation. And always return a Result<T>
sealed class . In the cases of writing the db like insert, return Result<Unit>.Rafael Tonholo
06/07/2024, 1:47 PMIO
dispatcher behind the scenes when dealing with coroutines, however, it also handles non-coroutines cases. That is why you need to "instruct" Room on how you want to retrieve your data.
If you plan to use Room with coroutines, you must use suspend
functions or functions that return `Flow`s. If your functions return a Flow
, you don't need to make them suspend
.
Here is a good read about Room with Coroutines that explains the difference between a function without and with a suspend
modifier.
And here is a good read about using Room with Flow
There are cases where using only suspend
functions is the best option and cases where using `Flow`s would fit better.
I suggest taking the time to read the Kotlin coroutines documentation. It will give you a better understanding of when to use the suspend
modifier and when it's unnecessary.