简体   繁体   English

等效于RxJava的RxJS.pausable(Observable)

[英]equivalent of RxJS.pausable(Observable) for RxJava

I search for a equivalent of RxJS.pausable(Observable) for RxJava. 我搜索RxJava的等效RxJS.pausable(Observable)

Currently I have the following but it looks a little bit strange. 目前,我有以下内容,但看起来有些奇怪。 Is there a better way? 有没有更好的办法?

PublishSubject<Boolean> allValidSubject = PublishSubject.create();
PublishSubject<Void> clickSubject = PublishSubject.create();

allValidSubject
      .switchMap(valid -> valid ? clickSubject : Observable.empty())
      .skipUntil(allValidSubject)
// ...

At the end I have two observables. 最后,我有两个观察值。 One for input validation and one for a send button click event. 一个用于输入验证,另一个用于发送按钮单击事件。

I think something like this would do it. 我认为这样可以做到。

Observable<String> event = Observable.just("My Input");
// false - paused by default
final BehaviorSubject<Boolean> pauser = BehaviorSubject.create(false);

event
    .flatMap(new Func1<String, Observable<String>>() {
        @Override
        public Observable<String> call(final String input) {
            return pauser
                    .distinctUntilChanged()
                    .filter(new Func1<Boolean, Boolean>() {
                        @Override
                        public Boolean call(Boolean resumed) {
                            return resumed;
                        }
                    })
                    .map(new Func1<Boolean, String>() {
                        @Override
                        public String call(Boolean resumed) {
                            return input;
                        }
                    });
        }
    })
    .subscribe(new Action1<String>() {
        @Override
        public void call(String input) {
            // handle input
        }
    });

To resume/pase: 要恢复/继续:

pauser.onNext(true);
pauser.onNext(false);

Event observable can be replaced with combineLatest how suggested above, but it is per use case, and still can be flatMapped. 可观察到的事件可以用上面建议的CombineLatest替换,但这是针对每个用例的,仍然可以进行flatMapped。 Same fasle/true could be pushed onto pauser, that's where distrinctUntilChanged kicks in to avoid resume or pause if already resumed/paused. 可以将相同的fasle / true推入暂停器,这是distrinctUntilChanged插入的地方,以避免已恢复/已暂停的恢复或暂停。

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

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