Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room with RxJava handle empty query result

Trying to test new Android Room librarty with RxJava adapter. And I want to handle result if my query returns 0 objects from DB:

So here is DAO method:

@Query("SELECT * FROM auth_info")
fun getAuthInfo(): Flowable<AuthResponse>

And how I handle it:

database.authDao()
    .getAuthInfo()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .switchIfEmpty { Log.d(TAG, "IS EMPTY") }
    .firstOrError()
    .subscribe(
            { authResponse -> Log.d(TAG, authResponse.token) },
            { error -> Log.d(TAG, error.message) })

My DB is empty, so I expect .switchIfEmty() to work, but none of handling methods is firing. Neither .subscribe() nor .switchIfEmpty()

like image 201
Nikita Unkovsky Avatar asked May 27 '17 10:05

Nikita Unkovsky


2 Answers

Db Flowables are observable (so they keep dispatching if database changes) so it never completes. You can try returning List<AuthResponse>. We've considered back porting an optional but decided not to do it, at least for now. Instead, we'll probably add support for Optional in different known libraries.

like image 50
yigit Avatar answered Oct 19 '22 03:10

yigit


In version 1.0.0-alpha5, room added support of Maybe and Single to DAOs, so now you can write something like

@Query("SELECT * FROM auth_info")
fun getAuthInfo(): Maybe<AuthResponse>

You can read more about it here

like image 42
J-rooft Avatar answered Oct 19 '22 04:10

J-rooft