简体   繁体   English

等待以前的Rx Observable完成

[英]Wait for previous Rx Observable to Finish

Hi I'm using RxJava for my disk storage get and set operations. 嗨,我正在使用RxJava进行磁盘存储的获取和设置操作。 Basically I have a method like this: 基本上我有这样的方法:

public Observable<String> getStorageItem(String id, String type) {
    return Observable.defer(new Func0<Observable<String>>() {
        // Run db operations to get storage item.
    }
}

The problem is that it's possible this method getStorageItem(...) gets subscribed to multiple times in a row. 问题在于该方法getStorageItem(...)可能连续多次被预订。 And the DB operations within the observable cannot run concurrently. 并且可观察范围内的数据库操作不能同时运行。 What's my best option here? 我最好的选择是什么? Should I manually create some sort've queue? 我应该手动创建某种排序队列吗? Or does RxJava have some kind of tool that allows me to block the operation until a previous one is complete? 还是RxJava有某种工具可以让我阻止该操作,直到上一个操作完成?

You can use a subscribeOn with a single-threaded scheduler created from an ExecutorService to make sure there's only one DB operation in progress: 您可以将subscribeOn与从ExecutorService创建的单线程调度程序一起使用,以确保只有一个DB操作正在进行中:

ExecutorService exec = Schedulers.newSingleThreadExecutor();
Scheduler s = Schedulers.from(exec);

public Observable<String> getStorageItem(String id, String type) {
    return Observable.fromCallable(() -> {
        // Do DB operations 
    });
}

getStorageItem("1", "2").subscribeOn(s).subscribe(...);
getStorageItem("2", "4").subscribeOn(s).subscribe(...);
getStorageItem("3", "6").subscribeOn(s).subscribe(...);

But note that by moving the computation off the caller's thread, it may execute any time. 但是请注意,通过将计算移出调用者的线程,它可以随时执行。 If you need to wait for it individually (because the getStorageItem is already called on some thread), you can apply toBlocking() after subscribeOn . 如果你需要等待它单独(因为getStorageItem已经呼吁一些线程),就可以申请toBlocking()subscribeOn

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

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