首页 > 解决方案 > 邮编清单可填写

问题描述

我有一个包含媒体播放器的 Sound 类,我想编写一个函数来接收声音列表并全部播放,该函数应该返回一个 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()???

标签: androidrx-java

解决方案


您可以使用concat, 从文档

返回一个 Completable,它仅在所有源一个接一个地完成时才完成。

您可以执行以下操作:

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

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


推荐阅读