繁体   English   中英

如何处理可观察对象发出的项目并访问另一个对象的值?

[英]How to process items emitted by an Observable with access to values from another?

我需要执行一个异步call_1 ,捕获其可观察到的reply_1 ,然后再进行一次异步call_2 ,在处理其reply_2我还需要访问reply_1

我已经尝试过类似的东西:

public rx.Observable<Game> findGame(long templateId, GameModelType game_model, GameStateType state) {

rx.Observable<RxMessage<byte[]>> ebs = context.getGameTemplate(templateId);

return context.findGame(templateId, state) // findGame returns rx.Observable<RxMessage<byte[]>>

    .flatMap(new Func1<RxMessage<byte[]>, rx.Observable<Game>>() {

        @Override
        public Observable<Game> call(RxMessage<byte[]> gameRawReply) {

            Game game = null;

            switch(game_model) {

                case SINGLE: {

                    ebs.subscribe(new Action1<RxMessage<byte[]>>() {

                        @Override
                        public void call(RxMessage<byte[]> t1) {

                            game = singleGames.get(0);

                        }
                    });
                }
            }

            return rx.Observable.from(game);
        }
    });
}

由于gamefinal问题,我仍然无法编译这种方法。

这是解决此问题的正确方法,还是有一种很自然的方法来完成我要尝试的工作。

如果我了解您要正确执行的操作,则认为解决此问题的自然方法是zip

您有两个Observables异步发出其结果,即ebscontext.findGame(...)的返回值。

您可以通过执行以下操作来组合其结果:

public rx.Observable<Game> findGame(long templateId, GameModelType game_model, GameStateType state) {

    rx.Observable<RxMessage<byte[]>> ebs = context.getGameTemplate(templateId);
    rx.Observable<RxMessage<byte[]>> gameObs = context.findGame(templateId, state);

    return Observable.zip(gameObs, ebs, new Func2<RxMessage<byte[]>, RxMessage<byte[]>, Game>() {

        @Override
        public Game call(RxMessage<byte[]> gameRawReply, RxMessage<byte[]> t1) {

            Game game = null;

            switch(game_model) {
                case SINGLE: {
                    game = singleGames.get(0);
                }
            }

            return game;
        }
    });
}

两个源Observable都调用它们的onNext时,将调用Func2-zip的第三个参数。 它将用于将它们发出的值合并为Game类型的新值,并将其发送给所得Observable的订户。

编辑:更多信息...

请注意,我将call()的返回值从Observable<Game>更改为Game。 否则,zip的结果将不是Observable<Game>而是Observable<Observable<Game>> 与map和flatMap不同,rx中只有zip-没有flatZip。 但是,由于您始终希望为每对输入项准确地发布一个游戏(一个来自ebs,一个来自gameObs),所以在这种情况下这不是问题。

而且,现在可以将Func2的call()进一步简化为:

@Override
public Game call(RxMessage<byte[]> gameRawReply, RxMessage<byte[]> t1) {

    switch(game_model) {
        case SINGLE: {
            return singleGames.get(0);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM