Immediate debounce in Rx

后端 未结 4 1670
南笙
南笙 2021-02-02 11:59

I am looking an operator to debounce a series of event, let us say user\'s click. The input and output should be like this:

interval :      ->            


        
4条回答
  •  耶瑟儿~
    2021-02-02 12:33

    Edit: Based on the clarifications, RxJava doesn't have an operator for this type of flow but it can be composed from a non-trivial set of other operators:

    import java.util.concurrent.TimeUnit;
    
    import rx.Observable;
    
    public class DebounceFirst {
    
        public static void main(String[] args) {
            Observable.just(0, 100, 200, 1500, 1600, 1800, 2000, 10000)
            .flatMap(v -> Observable.timer(v, TimeUnit.MILLISECONDS).map(w -> v))
            .doOnNext(v -> System.out.println("T=" + v))
            .compose(debounceFirst(500, TimeUnit.MILLISECONDS))
            .toBlocking()
            .subscribe(v -> System.out.println("Debounced: " + v));
        }
    
        static  Observable.Transformer debounceFirst(long timeout, TimeUnit unit) {
            return f -> 
                f.publish(g ->
                    g.take(1)
                    .concatWith(
                        g.switchMap(u -> Observable.timer(timeout, unit).map(w -> u))
                        .take(1)
                        .ignoreElements()
                    )
                    .repeatWhen(h -> h.takeUntil(g.ignoreElements()))
                );
        }
    }
    

提交回复
热议问题