Rx java RXJava/Kotlin-将单个结果链接到一个
我有一个问题,我不知道如何用更好的方法来解决它。问题是我请求SpotifyWebAPI,在某些方法中返回艺术家图像,而在另一些方法中仅获取基本的艺术家信息 我有两种方法:Rx java RXJava/Kotlin-将单个结果链接到一个,rx-java,system.reactive,rx-kotlin,Rx Java,System.reactive,Rx Kotlin,我有一个问题,我不知道如何用更好的方法来解决它。问题是我请求SpotifyWebAPI,在某些方法中返回艺术家图像,而在另一些方法中仅获取基本的艺术家信息 我有两种方法: fun getAlbum(albumId: String): Single<SpotifyAlbumDTO> fun getArtist(artistId: String): Single<SpotifyArtistDTO> 您可以使用Pair with flatMap将结果包装在一起: _spot
fun getAlbum(albumId: String): Single<SpotifyAlbumDTO>
fun getArtist(artistId: String): Single<SpotifyArtistDTO>
您可以使用Pair with flatMap将结果包装在一起:
_spotifyService.getAlbum(albumId).flatMap { spotifyAlbum ->
_spotifyService.getArtist(spotifyAlbum.artist.id)
.flatMap { artist ->
Single.just(spotifyAlbum, artist)
}
}.subscribe { pair: Pair<Album, Artist> ->
// grab results
val album = pair.first
val artist = pair.second
}
平行解
要组合多个数据源,最好的运算符是:
谢谢,这是一个伟大的演讲!我想知道其他的解决方案,我认为必须存在一个操作符来积累以前的结果,因为如果你想连接更多的呼叫,我认为这不是最好的。这不是一个奇怪的案例,必须有更好的解决方案!对不起,我不能使用zip,因为在执行getAlbum之前我不知道artistId。我误解了你的问题,我已经更新了我的答案。谢谢!这就是我需要的
fun getAlbum(albumId: String): Single<Album> {
return Single.create { emitter ->
_spotifyService.getAlbum(albumId).subscribe { spotifyAlbum ->
_spotifyService.getArtist(spotifyAlbum.artist.id).subscribe { spotifyArtist ->
val artistImage = spotifyArtist.imageUrl
spotifyAlbum.artist.image = artistImage
emitter.onNext(spotifyAlbum.toAlbum())
}
}
}
}
_spotifyService.getAlbum(albumId).flatMap { spotifyAlbum ->
_spotifyService.getArtist(spotifyAlbum.artist.id)
}.flatMap { spotifyArtist ->
// Here I don't have the album and I can't to asign the image
}
_spotifyService.getAlbum(albumId).flatMap { spotifyAlbum ->
_spotifyService.getArtist(spotifyAlbum.artist.id)
.flatMap { artist ->
Single.just(spotifyAlbum, artist)
}
}.subscribe { pair: Pair<Album, Artist> ->
// grab results
val album = pair.first
val artist = pair.second
}
Single.zip(getAlbum(albumId), getArtist(artistId),
BiFunction<SpotifyAlbumDTO, SpotifyArtistDTO, SpotifyAlbumDTO> { album, artist ->
val artistImage = artist.imageUrl
album.artist.image = artistImage
album //return value of the merged observable
}
).subscribe { album: SpotifyAlbumDTO?, error: Throwable? ->
emitter.onNext(album.toAlbum())
}
getAlbum(albumId)
.toObservable()
.flatMap({album: SpotifyAlbumDTO -> getArtist(album.artist.id).toObservable()},
{ album:SpotifyAlbumDTO, artist:SpotifyArtistDTO ->
album.artist.image = artist.imageUrl
album
})
}?.subscribe { album: SpotifyAlbumDTO ->
print(album)
}