Search code examples
androidrx-androidrx-kotlin2

How to implement different kinds of return to the same query using Room and Android Rx?


I'm facing this problem. Im using room to create the local database of my app. Let's say i have an Entity call User and a UserDao. It looks like this:

@Dao
interface UserDao: BaseDao<User>{
    @Query("SELECT * FROM user WHERE remote_id = :remoteId")
    fun getUser(remoteId : Long) : Single<User>
}

Nothing weird in this point, but what i want to do is be able to Changue the type of return in these functions. I want this because sometimes i need to get a Single but in other cases i need to get a Flowable. In this two cases the query is the same an the only thing than chagues is the type of return and i don't want to do something like this.

@Dao
interface UserDao: BaseDao<User>{

    @Query("SELECT * FROM user WHERE remote_id = :remoteId")
    fun getUserSingle(remoteId : Long) : Single<User>

    @Query("SELECT * FROM user WHERE remote_id = :remoteId")
    fun getUserFlowable(remoteId : Long) : Flowable<User>
 } 

Any idea how to do this in a clean way?


Solution

  • You can just use your Single<User> and call toFlowable() on it. Something like getUserSingle().toFlowable() on your dao object.

    EDIT

    You can us flowable operator and call it something like getUserFlowable.firstOrError() . because from the documentation

    Returns a Single that emits only the very first item emitted by this Flowable or signals a {@link NoSuchElementException} if this Flowable is empty