RxJava队列多个可观察对象

时间:2017-01-09 10:19:45

标签: java android queue rx-java

我有很多Observable方法。我希望在之前完成之后再次运行。

A类

public Observable<String> method1(){
    // complex stuff (10 sec)
}

public Observable<String> method2(){
    // another complex stuff (10 sec)
}

B类

foo.method1().subscribe(...);
foo.method2().subscribe(...);
foo.method1().subscribe(...);
foo.method1().subscribe(...);

我想一个接一个地运行它...而且最难的是:我无法改变 B类。我必须更改 A类才能实现我的目标。有什么想法吗?

我可以使用flatMat(...)concatMap(...) B类中执行此操作,但我无法更改 B类

1 个答案:

答案 0 :(得分:0)

看起来很糟糕,但应该做好。 Sempahore将确保只有一个线程正在处理数据。请注意,此解决方案不保证操作顺序。

public class  A {

    private final Semaphore semaphore = new Semaphore(1);

    public Observable<String> method1() {
        try {
            semaphore.acquire();
            // complex stuff (10 sec)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public Observable<String> method2() {
        try {
            semaphore.acquire();
            // another complex stuff (10 sec)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}