Saturday, 22 October 2022

What will happen if the record searched by ID doesn't exist when I use Room?

The Code A is from the official sample project.

The fun getTopicEntity will return a flow based the parameter topicId, I wonder whether the app will crash if the record based input topicId doesn't exist.

In my mind, fun getTopicEntity(topicId: String): Flow<TopicEntity> requires to return Flow<TopicEntity>, Flow<TopicEntity> will not be generated if the record doesn't exist, so the app will crash. Is it right?

Code A

@Dao
interface TopicDao {
    @Query(
        value = """
        SELECT * FROM topics
        WHERE id = :topicId
    """
    )
    fun getTopicEntity(topicId: String): Flow<TopicEntity>

    ...
}


class OfflineFirstTopicsRepository @Inject constructor(
    private val topicDao: TopicDao,
    private val network: NiaNetworkDataSource,
) : TopicsRepository {
  
    override fun getTopic(id: String): Flow<Topic> =
        topicDao.getTopicEntity(id).map { it.asExternalModel() }
    
    ...
}


from What will happen if the record searched by ID doesn't exist when I use Room?

No comments:

Post a Comment