Andy Cass
Andy Cass

Reputation: 446

Filter using Single<Boolean>

I want to filter a stream(), the filter must be supplied with a predicate how can i achieve this using RxJava, i am using Room Persistence Database, i want to add new fields if the database does not already contain them, my problem is with the doesDatabaseContainSong() method.

I'm new to RX Java, the code is a mix of Kotlin and Java

    // 1. ADD NEW SONGS TO DATABASE
songs.stream()
        .filter(song -> !doesDatabaseContainSong(song, mViewModel))
        .forEach(this::addSongToDatabase);

I want the following function(doesDatabaseContainSong) to return a boolean instead it returns Single< Int >

public static boolean doesDatabaseContainSong(Song song, SongViewModel model) {
    int result = model.doesDatabaseContainSong(song.getId(), Type.GOOGLE_DRIVE.name());
    return result != 0;
}

The View Model

fun doesDatabaseContainSong(mId: String): Single<Int> {
    return repository.doesDatabaseContainSong(mId)
}

The Repository

fun doesDatabaseContainSong(mId: String): Single<Int> {
    return songDao.doesDatabaseContainSong(mId)
}

The DAO

@Query("SELECT COUNT(id) from song_table WHERE id = :mId")
fun doesDatabaseContainSong(mId: String): Single<Int>

Upvotes: 1

Views: 1083

Answers (1)

arungiri_10
arungiri_10

Reputation: 988

The DAO (changed return type to Boolean)

@Query("SELECT COUNT(id) from song_table WHERE id = :mId")
fun doesDatabaseContainSong(mId: String): Single<Boolean>

The Repository (changed return type to Boolean)

fun doesDatabaseContainSong(mId: String): Single<Boolean> {
    return songDao.doesDatabaseContainSong(mId)
}

The View Model (changed return type to Boolean)

fun doesDatabaseContainSong(mId: String): Single<Boolean> {
    return repository.doesDatabaseContainSong(mId)
}

(changed return type to Boolean)

public static Single<Boolean> doesDatabaseContainSong(Song song, SongViewModel model) {
    return model.doesDatabaseContainSong(song.getId(), Type.GOOGLE_DRIVE.name());
}

Now final code:

songs
    .stream()
    .flatMap(doesContainSong -> doesDatabaseContainSong(song, mViewModel))
    .filter(doesContainSong -> !doesContainSong)
    .forEach(this::addSongToDatabase);

Hope this helps.

Upvotes: 1

Related Questions