假设我有一个Observable<Player>
,我想将它映射到另一个Observable<Integer>
,其中Integer
等于player.height
,但有一个条件:我想映射所有玩家,但第一个和最后一个(我们应该再检查一个他们)。所以在迭代编程中它会像这样:
heights = []
num_of_players = len(players)
for idx in len(num_of_players):
if (idx == 0 or idx == num_of_players - 1):
if (isGoodEnough(players[idx]):
heights.append(player.height)
else:
heights.append(player.height)
return height
我如何以 Rx 的方式重写它(你应该假设我得到的是 Observable 而不是 List)?
鉴于:
Observable<Player> players;
Single<Integer> playerHeight(int playerId);
您必须使用publish(Function)
s将序列拆分为 first、middle 和 last,然后将它们组合在一起:
players
.publish(sharedPlayers -> {
return Observable.merge(
// work only on the very first player
sharedPlayers.take(1)
.filter(firstPlayer -> isGoodEnough(firstPlayer))
.flatMapSingle(firstPlayer -> playerHeight(firstPlayer.playerId)),
// work with not the first and not the last
sharedPlayers.skip(1).skipLast(1)
.flatMapSingle(midPlayers -> playerHeight(midPlayers .playerId)),
// work with the last which shouldn't be the first again
sharedPlayers.skip(1).takeLast(1)
.filter(lastPlayer -> isGoodEnough(lastPlayer))
.flatMapSingle(lastPlayer-> playerHeight(lastPlayer.playerId))
);
})
.subscribe(/* ... */);
请根据需要调整此解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句