coinhndp
coinhndp

Reputation: 2481

Zip list completable

I have the class Sound which contains a media player, I want to write a function that receives a list of sound and play them all, that function should return a Completable

interface MediaPlayer {
    fun play(): Completable
}

class Sound(val title, val mediaPlayer: MediaPlayer)

//In other class, we have a list of sound to play
val soundList = List<Sound>(mockSound1, mockSound2,..,mockSound10)

fun playSound(): Completable {
    return mockSound1.play()
}

fun playAllSounds(): Completable {
    soundList.forEach(sound -> sound.mediaPlayer.play()) //Each of this will return Completable. 

//HOW to return Completable
return ??? do we have somthing like zip(listOf<Completable>)
}


//USE
playSound().subscrible(...) //Works well

playAllSounds().subscribe()???

Upvotes: 1

Views: 5429

Answers (2)

carlo.marinangeli
carlo.marinangeli

Reputation: 3048

You can try Completable.merge. it will subscribe to all the Completables at once. Here is the link to the docs

Upvotes: 2

Ahmed Ashraf
Ahmed Ashraf

Reputation: 2835

You can use concat, from the docs

Returns a Completable which completes only when all sources complete, one after another.

You can do something like:

fun playAllSounds(): Completable {
    val soundsCompletables = soundList.map(sound -> sound.mediaPlayer.play())
    return Completable.concat(soundCompletables)
}

Ref: http://reactivex.io/RxJava/javadoc/io/reactivex/Completable.html#concat-java.lang.Iterable-

Upvotes: 3

Related Questions