如何在不立即订阅的情况下调用RxJava Observable?

时间:2015-11-18 16:16:16

标签: java multithreading rx-java

我有一个返回字符串模板的java方法。我想对远程api进行2次异步调用,每次调用都会返回一个数字,然后我想计算这两个数字的总和并在返回之前将其放入模板中。

所以我有这个java代码来完成这个任务:

private Observable<Integer> createObservable() {
    Observable<Integer> obs = Observable.create(new OnSubscribe<Integer>() {

        public void call(Subscriber<? super Integer> t) {
            System.out.println("Call with thread : " + Thread.currentThread().getName());
            //FAKE CALL TO REMOTE API => THE THREAD IS SLEEPING DURING 4 SECCONDS
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t.onNext(new Random().nextInt(10));
            t.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread());

    return Observable
        .merge(obs, obs)
        .reduce(new Func2<Integer, Integer, Integer>() {

            public Integer call(Integer t1, Integer t2) {
                return t1 + t2;
            }
        });     
}

public String retrieveTemplate() {
    //I WANT TO START THE WORK OF THE OBSERVABLE HERE BUT I DON'T KNOW HOW TO DO IT

    //DO THINGS IN THE MAIN THREAD
    //HERE I JUST INITIALIZE A STRING BUT WE COULD IMAGINE I WOULD DO MORE THINGS
    String s = "The final Number is {0}";
    System.out.println(Thread.currentThread().getName() + " : the string is initialized");

    //I WAIT FOR THE OBSERVABLE RESULT HERE
    int result = createObservable().toBlocking().first();

    return MessageFormat.format(s, result);
}

此代码的输出是正确的(创建两个线程来调用远程api)

  

main:字符串已初始化

     

使用线程调用:RxNewThreadScheduler-1

     

使用主题调用:RxNewThreadScheduler-2

     

最终的数字是2

我想在方法 retrieveTemplate 的开头调用RxJava Observable(为了尽快调用远程api)并在调用之前等待结果MessageFormat.format ,但我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

假设整个创建过程有效,您可能希望通过转换源可观察对象将整个计算绑定到订阅时刻:

public Observable<String> retrieveTemplate() {
    return createObservable().map(result -> {
        String s = "The final Number is {0}";
        System.out.println(Thread.currentThread().getName() + " : the string is initialized");

        return MessageFormat.format(s, result);
    });
}

当您订阅retrieveTemplate的结果observable时 - 您实际上开始了整个计算:

// some other place in the code
retrieveTemplate().subscribe(template -> doStuffWithTemplate(template))