假设我有一个function0: function(e) {
e.preventDefault();
var valid = false;
var dfd = $.Deferred();
//$.when(function1(e)).done(function(v){
// had to change .done to .then
$.when(function1(e)).then(function(v){
valid = v; // -> right here valid is undefined
if(!valid) {
alertSomething();
return;
}
// had to change the scope and make it inside the .then so that it only executes when I have the value
keepExecutingCode();
dfd.resolve();
});
dfd.promise();
},
,我想将其映射到另一个Observable<Player>
,其中Observable<Integer>
等于Integer
,但是有一个条件:我想映射所有玩家,但是第一个和最后一个(我们应该为他们再检查一下)。所以在迭代编程中它会像这样:
player.height
如何以Rx方式重写(你应该假设我给了Observable而不是List)?
答案 0 :(得分:1)
假设:
Observable<Player> players;
Single<Integer> playerHeight(int playerId);
您必须使用publish(Function)
将序列分为第一个,中间一个和最后一个,然后将它们组合在一起:
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(/* ... */);
请根据需要调整此解决方案。