Analysis of switchMap and debounce in Rxjava's PublishSubject

Recently, in order to realize the search association function of Taobao, we need to use retrofit2+rxjava2 to realize the basic functions.
Among them, Rxjava needs to use a class called PublishSubject, and this class has a method called debounce for us to implement:
When the input box changes, the event will not be published immediately, but wait for xxms. If the input box does not change in this event, the event will be sent; otherwise, wait for xxms after receiving new keywords.
The example code is as follows:

PublishSubject<String> mPublishSubjectï¼›
mPublishSubject.debounce(200, TimeUnit.MILLISECONDS)

The first parameter of the debounce method is time, and the second is the unit of time
The source code is as follows:

public final Observable<T> debounce(long timeout, TimeUnit unit)
  return this.debounce(timeout, unit, Schedulers.computation());

 public enum TimeUnit {

    private TimeUnit() {

Next, use the filter operator. Filter function: filter the results generated by the source Observable according to the specified conditions. Only the results that meet the conditions will be submitted to the subscriber.

PublishSubject.debounce(200, TimeUnit.MILLISECONDS) 
                .filter(new Predicate<String>() { 
             public boolean test(String s) throws Exception {
                        return s.length() > 0;

By using the switchMap operator, when the request of abc is initiated, even if the result of ab is returned, it will not be sent to the downstream, so as to avoid the problem of mismatch between the search terms and association results described earlier. The switchMap operator saves the results of the latest Observable and discards the old results.

.switchMap(new Function<String, ObservableSource<String>>() {

        public ObservableSource<String> apply(String query)
         throws Exception {
         //Here is imitating to request data in the background
              return getSearchObservable(query);

      .subscribe(new DisposableObserver<String>() {

          public void onNext(String s) {
           public void onError(Throwable throwable) {


                    public void onComplete() {


PublishSubject does not trigger the subscription event immediately when subscribing. It allows us to manually call onNext(),onError(),onCompleted at any time to trigger the event.
For example:

private void startSearch(String query) {

Finally: I hope to be helpful to you, and like can point a praise, to encourage me, I will be grateful!

Added by Andy82 on Wed, 01 Apr 2020 09:58:21 +0300