Home > Mobile >  Android Room DAO Java interface with @Query stored in a public string: is this practice as bad as it
Android Room DAO Java interface with @Query stored in a public string: is this practice as bad as it

Time:10-27

Using Room and RxJava3, my DAO interfaces always have methods with different return types (Maybe and Flowable) but with the exact same query. This is how I solve an important issue, which is that whenever I use Flowables, I want an empty list emitted immediately when the table is empty (rather than nothing at all).

Duplicating the query string may introduce bugs if I ever get sloppy and forget to update all of them. Now that I found I can still get syntax highlighting in Android Studio when storing the query, I came up with the following.

String query = "SELECT * FROM MyObject"; // public, as DAO is a public java interface

@Query(query)
Maybe<List<MyObject>> maybeMyObjectList();

@Query(query)
Flowable<List<MyObject>> flowableMyObjectList();

This enables me to do things like flowableMyObjectList().startWith(maybeMyObjectList().defaultIfEmpty(Collections.emptyList())).distinctUntilChanged()

Still, having SQL queries stored in a public string feels like a bad idea, security-wise. On the other hand, I don't think the database schema in my app bundle is supposed to be secret anyway. Can anyone with a better knowledge than mine confirm that it is a bad as it sounds, or better propose a workaround?

CodePudding user response:

Instead of an interface you can use an abstract class, thus you can then have methods with bodies and private variables.

You then have to make the methods abstract.

So you could have:-

@Dao
abstract class TheDao {

    private static final String query = "SELECT * FROM MyObject";

    @Query(query)
    abstract Maybe<List<MyObject>> maybeMyObjectList();

    @Query(query)
    abstract Flowable<List<MyObject>> flowableMyObjectList();
}
  • Related