我有一个Sound类,其中包含一个媒体播放器,我想编写一个接收声音列表并全部播放的函数,该函数应返回一个 可完成
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()???
答案 0 :(得分:1)
您可以从文档中使用concat
返回一个Completable,该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-
答案 1 :(得分:1)
您可以尝试Completable.merge
。它将立即订阅所有完成项。
这是link to the docs