RxJava常用操作符

版权声明:本文为Mr.release原创文章,转载请标明出处

  • 创建操作符
  • 变换操作符
  • 过滤操作符
  • 组合操作符
  • 辅助操作符
  • 错误处理操作符
  • 布尔操作符
  • 条件操作符
  • 转换操作符

创建操作符

1.from操作符

	//from操作符,创建以数组内容发送事件的Observable
    String[] data = new String[]{"zhangsan", "lisi"};
    Observable.from(observableArr).subscribe(onNextAction, onErrorAction);

		//onNext响应成功方法的包装
    Action1<T> onNextAction = new Action1<T>() {
        @Override
        public void call(T t) {
            Toast.makeText(getActivity(), "onNext:" + t, Toast.LENGTH_SHORT).show();
        }
    };
    //onError返回失败信息方法的包装
    Action1<Throwable> onErrorAction = new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            Toast.makeText(getActivity(), "onError,Error Info is:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }
    };

2.just操作符

	//just操作符,创建将逐个内容进行发送的Observable,其内部发送内容在内部以from的操作符的方式进行转换
	Observable.just("Alex", "Payne").subscribe(onNextAction);

3.interval操作符

	//interval操作符,创建以1秒为事件间隔发送整数序列的Observable
	Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).subscribe(onNextAction);

4.range操作符

	 //range操作符,创建以发送范围内的整数序列的Observable
	 Observable.range(0, 3).subscribe(onNextAction);

5.repeat操作符

	//repeat操作符,创建一个以N次重复发送数据的Observable
	Observable.range(0, 3).repeat(2).subscribe(onNextAction);

变换操作符

1.map操作符

	//map操作符,通过指定一个Func,将Observable转换为另一个Observable对象并发送
    Observable.just("Alex_Payne")
              .map(new Func1<String, String>() {
                  @Override
                  public String call(String s) {
                      return "My Name is" + s;
                  }
              }).subscribe(onNextAction);

2.flatMap操作符

 	//flatMap操作符,将Observable发送的数据集合转换为Observable集合
	//flatMap的合并运行允许交叉,允许交错的发送事件
	String[] observableArr = {"Alex", "Max", "Bruce", "Frank", "Tom"};
	Observable.from(observableArr).flatMap(new Func1<String, Observable<String>>() {
	      @Override
	      public Observable<String> call(String s) {
	         return Observable.just("My Name is:" + s);
	      }
	 }).subscribe(onNextAction);

3.concatMap操作符

	//concatMap操作符,将Observable发送的数据集合转换为Observable集合
	//解决了flatMap的交叉问题,将发送的数据连接发送
	String[] observableArr = {"Alex", "Max", "Bruce", "Frank", "Tom"};
	Observable.from(observableArr).concatMap(new Func1<String, Observable<String>>() {
	      @Override
	      public Observable<String> call(String s) {
	         return Observable.just("My Name is:" + s);
	      }
	 }).subscribe(onNextAction);

4.cast操作符

	//cast操作符,将类对象进行转换
	Object[] objectsArr = {"1", "2", "3"};
	Observable.from(objectsArr).cast(String.class).subscribe(onNextAction);

5.flatMapIterable操作符

	//将数据集合转换为Iterable,在Iterable中对数据进行处理
	Observable.just(1, 2, 3).flatMapIterable(new Func1<Integer, Iterable<Integer>>() {
	   @Override
	   public Iterable<Integer> call(Integer number) {
	         ArrayList<Integer> mList = new ArrayList<>();
	         mList.add(1000 + number);
	         return mList;
	     }
	}).subscribe(onNextAction);

6.buffer操作符

	//buffer操作符,将原有Observable转换为一个新的Observable,这个新的Observable每次发送一组值,而不是一个个进行发送
	Observable.just(1, 2, 3, 4, 5, 6)
	     .buffer(3).subscribe(new Action1<List<Integer>>() {
	     @Override
	     public void call(List<Integer> mList) {
	          for (Integer i : mList) {
	               Toast.makeText(getActivity(), "new Number i is:" + i, Toast.LENGTH_SHORT).show();
	          }
	          Toast.makeText(getActivity(), "Another request is called", Toast.LENGTH_SHORT).show();
	        }
	    });

7.groupBy操作符

	//groupBy操作符,可以做分组操作
	Observable.range(0, 10).groupBy(new Func1<Integer, Integer>() {
	    @Override
	    public Integer call(Integer num) {
	       return num % 3;
	       }
	  }).subscribe(new Action1<GroupedObservable<Integer, Integer>>() {
	    @Override
	    public void call(final GroupedObservable<Integer, Integer> groupedObservable) {
	       groupedObservable.subscribe(new Action1<Integer>() {
	         @Override
	         public void call(Integer num) {
	               Toast.makeText(getActivity(), "当前的组别是:" + groupedObservable.getKey() + "组别内的数字是:" + num, Toast.LENGTH_SHORT).show();
	             }
	        });
	    }
	});

过滤操作符

1.filter操作符

	//filter过滤操作符,对Observable发送的内容根据自定义的规则进行过滤
	Observable.range(0, 5).filter(new Func1<Integer, Boolean>() {
	   @Override
	   public Boolean call(Integer num) {
	            return num > 2;//自定义的条件,只有符合条件的结果才会提交给观察者
	   }
	 }).subscribe(onNextAction);

2.elementAt操作符

	//elementAt操作符,用于返回指定位置后一位的数据,即脚标+1的数据
	//在这里发送0、1、2、3、4,脚标为3的数据为2,发送其后一位数据3
	Observable.range(0, 5).elementAt(3).subscribe(onNextAction);

3.distinct操作符

	//distinct操作符,用于Observable发送的元素的去重
	Observable.just(1, 1, 2, 2, 2, 3).distinct().subscribe(onNextAction);

4.skip操作符

	//skip操作符,用于Observable发送的元素前N项去除掉
	Observable.range(0, 5).skip(2).subscribe(onNextAction);

5.take操作符

	//take操作符,用于Observable发送的元素只取前N项
	Observable.range(0, 5).take(2).subscribe(onNextAction);

6.ignoreElements操作符

	//ignoreElements操作符,忽略掉源Observable发送的结果,只把Observable的onCompleted或onError发送
	Observable.range(0, 5).ignoreElements().subscribe(onNextAction, onErrorAction, onCompletedAction);

7.throttleFirst操作符

	//throttleFirst操作符,会定期发送这个时间段里源Observable发送的第一个数据
	//throttleFirst操作符默认在computaioin调度器上执行,其他的数据都会被过滤掉
	 Observable.create(new Observable.OnSubscribe<Integer>() {
	        @Override
	        public void call(Subscriber<? super Integer> subscriber) {
	             for (int i = 0; i < 10; i++) {
	                 subscriber.onNext(i);
	                 //线程休眠100毫秒
	                 try {
	                      Thread.sleep(100);
	                 } catch (InterruptedException e) {
	                 e.printStackTrace();
	                 }
	             }
	       }
	})
	.throttleFirst(200, TimeUnit.MILLISECONDS)
	.subscribe(onNextAction);

8.buffer操作符

	//throttleWithTimeout操作符
	//源发射数据时,如果两次数据的发射间隔小于指定时间,就会丢弃前一次的数据,直到指定时间内都没有新数据发射时才进行发射           
	Observable.create(new Observable.OnSubscribe<Integer>() {
	@Override
	 public void call(Subscriber<? super Integer> subscriber) {
	        subscriber.onNext(1);
	        try {
	             Thread.sleep(500);
	         } catch (InterruptedException e) {
	             throw Exceptions.propagate(e);
	         }
	        subscriber.onNext(2);
	        try {
	             Thread.sleep(500);
	         } catch (InterruptedException e) {
	             throw Exceptions.propagate(e);
	         }
	         subscriber.onNext(3);
	         try {
	            Thread.sleep(1000);
	          } catch (InterruptedException e) {
	              throw Exceptions.propagate(e);
	          }
	         subscriber.onNext(4);
	         subscriber.onNext(5);
	         subscriber.onCompleted();
	     }
	})
	.throttleWithTimeout(800, TimeUnit.MILLISECONDS)
	.subscribeOn(Schedulers.newThread())
	.observeOn(AndroidSchedulers.mainThread())
	.subscribe(onNextAction);

组合操作符

1.startWith组合操作符

	//startWith操作符,会在发送的数据之前插入数据
	Observable.range(3, 5).startWith(0, 10086).subscribe(onNextAction);

2.merge组合操作符

	//merge操作符,会将多个Observable对象合并到一个Observable对象中进行发送
	Observable<Integer> firstObservable = Observable.just(0, 1, 2).subscribeOn(Schedulers.io());
	Observable<Integer> secondObservable = Observable.just(3, 4, 5);
	Observable.merge(firstObservable, secondObservable).subscribe(onNextAction, onErrorAction);

3.concat组合操作符

	//concat操作符,会将多个Observable对象合并到一个Observable对象中进行发送,严格按照顺序进行发送
	Observable<Integer> firstObservable = Observable.just(0, 1, 2).subscribeOn(Schedulers.io());
	Observable<Integer> secondObservable = Observable.just(3, 4, 5);
	Observable.concat(firstObservable, secondObservable)
	       .subscribeOn(Schedulers.io())
	       .observeOn(AndroidSchedulers.mainThread())
	       .subscribe(onNextAction);

4.zip组合操作符

	//zip操作符,会将多个Observable对象转换成一个Observable对象然后进行发送,转换关系可根据需求自定义
	Observable<Integer> integerObservable = Observable.range(0, 4);
	Observable<String> stringObservable = Observable.just("a", "b", "c", "d");
	Observable.zip(integerObservable, stringObservable, new Func2<Integer, String, String>() {
	   @Override
	   public String call(Integer num, String info) {
	       //在这里的转换关系为将数字与字串内容进行拼接
	       return "数字为:" + num + "  字符为:" + info;
	   }
	}).subscribe(onNextAction);

5.combineLastest组合操作符

	//combineLastest操作符,会将多个Observable对象转换一个Observable对象然后进行发送,转换关系可以根据需求自定义
	//不同于zip操作符的是,会将最新发送的数据组合到一起
	integerObservable = Observable.just(1, 2, 3);
	stringObservable = Observable.just("a", "b", "c");
	Observable.combineLatest(integerObservable, stringObservable, new Func2<Integer, String, String>() {
	    @Override
	    public String call(Integer num, String info) {
	        //在这里的转换关系为将数字与字串内容进行拼接
	        return "数字为:" + num + "……字符为:" + info;
	    }
	}).subscribe(onNextAction);

辅助操作符

1.delay操作符

	//delay操作符可以让源Observable对象发送数据之前暂停一段制定的时间
	Observable.just(1, 2, 3)
		     .delay(2, TimeUnit.SECONDS)
		     .observeOn(AndroidSchedulers.mainThread())
		     .subscribe(onNextAction);

2.do操作符

	//doOnNext是do操作符中的一种
	Observable.range(0, 3).doOnNext(onNextAction).subscribe(onNextAction);	

3.subscribeOn辅助操作符

	Observable.just("当前的线程ID为" + Thread.currentThread().getName())
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(onNextAction);

4.observeOn辅助操作符

	 Observable.just("当前的线程ID为" + Thread.currentThread().getName())
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(onNextAction);   

5.timeout辅助操作符

	//timeout操作符,如果源Observable对象过了一段时间没有发送数据,timeout会以onError通知终止这个Observable
	Observable.create(new Observable.OnSubscribe<Integer>() {
	    @Override
	    public void call(Subscriber<? super Integer> subscriber) {
	        for (int i = 0; i < 5; i++) {
	            try {
	                Thread.sleep(i * 100);
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	            subscriber.onNext(i);
	        }
	    }
	}).timeout(200, TimeUnit.MILLISECONDS, Observable.just(100, 200))
	        .observeOn(AndroidSchedulers.mainThread())
	        .subscribe(onNextAction);

错误操作符

1.catch操作符

三种实现方案:onErrorReturn、onErrorResumeNext、onExceptionResumeNext。

	//onErrorReturn
	Observable.create(new Observable.OnSubscribe<Integer>() {
	    @Override
	    public void call(Subscriber<? super Integer> subscriber) {
	        for (int i = 0; i < 5; i++) {
	            if (i > 3) {
	                subscriber.onError(new Throwable("User Alex Defined Error"));
	            }
	            subscriber.onNext(i);
	        }
	    }
	}).onErrorReturn(new Func1<Throwable, Integer>() {
	    @Override
	    public Integer call(Throwable throwable) {
	        return 404;
	    }
	}).subscribe(onNextAction, onErrorAction, onCompletedAction);

	//onErrorResumeNext
	Observable.create(new Observable.OnSubscribe<Integer>() {
	    @Override
	    public void call(Subscriber<? super Integer> subscriber) {
	        for (int i = 0; i < 5; i++) {
	            if (i > 3) {
	                subscriber.onError(new Throwable("User Alex Defined Error"));
	            }
	            subscriber.onNext(i);
	        }
	    }
	}).onErrorResumeNext(new Func1<Throwable, Observable<? extends Integer>>() {
	    @Override
	    public Observable<? extends Integer> call(Throwable throwable) {
	        return Observable.just(100,101,102);
	    }
	}).subscribe(onNextAction,onErrorAction,onCompletedAction);

	//onExceptionResumeNext
	Observable.create(new Observable.OnSubscribe<Integer>() {
	    @Override
	    public void call(Subscriber<? super Integer> subscriber) {
	        for (int i = 0; i < 5; i++) {
	            if (i > 3) {
	                subscriber.onError(new Throwable("User Alex Defined Error"));
	            }
	            subscriber.onNext(i);
	        }
	    }
	}).onExceptionResumeNext(Observable.just(100,101,102)).subscribe(onNextAction,onErrorAction,onCompletedAction);

2.retry操作符

	//retry操作符,当遇到exception时会进行重试,重试次数可以由用户进行定义
	Observable.create(new Observable.OnSubscribe<Integer>() {
		@Override
		public void call(Subscriber<? super Integer> subscriber) {
		    for (int i = 0; i < 5; i++) {
		        if (i > 1) {
		            subscriber.onError(new Throwable("User Alex Defined Error"));
		        }
		        subscriber.onNext(i);
		    }
		}
	}).retry(2).subscribe(onNextAction,onErrorAction,onCompletedAction);

布尔操作符

1.all操作符

	Observable.just(1, 2, 3, 4).all(new Func1<Integer, Boolean>() {
	    @Override
	    public Boolean call(Integer num) {
	        return num > 3;
	    }
	}).subscribe(onNextAction, onErrorAction, onCompletedAction);

2.contains操作符

	Observable.just(1, 2, 3, 4).contains(2).subscribe(onNextAction, onErrorAction, onCompletedAction);

3.isEmpty操作符

	Observable.just(1, 2, 3, 4).isEmpty().subscribe(onNextAction, onErrorAction, onCompletedAction);

4.exists操作符

	Observable.just(1, 2, 3, 4).exists(new Func1<Integer, Boolean>() {
	    @Override
	    public Boolean call(Integer num) {
	        return num > 3;
	    }
	}).subscribe(onNextAction, onErrorAction, onCompletedAction);

5.sequenceEqual操作符

	Observable.sequenceEqual(Observable.just(1, 2, 3, 4), Observable.just(1))
		.subscribe(onNextAction, onErrorAction, onCompletedAction);

条件操作符

1.amb操作符

	//给定多个Observable,只让第一个发送数据的Observable发送数据
	Observable
	        .amb(Observable.range(0,3).delay(2000, TimeUnit.MILLISECONDS),Observable.range(100,3))
	        .subscribe(onNextAction);

2.defaultIfEmpty操作符

	//如果源Observable没有发送数据,则发送一个默认数据
	Observable.create(new Observable.OnSubscribe<Integer>() {
	    @Override
	    public void call(Subscriber<? super Integer> subscriber) {
	        subscriber.onCompleted();
	    }
	}).defaultIfEmpty(404).subscribe(onNextAction,onErrorAction,onCompletedAction);

转换操作符

1.toList操作符

	//toList操作符,将源Observable发送的数据组合为一个List集合
	//然后再次在onNext方法中将转换完的List集合进行传递
	Observable.just(1, 2, 3).toList().subscribe(new Action1<List<Integer>>() {
	    @Override
	    public void call(List<Integer> numList) {
	        for (Integer i : numList) {
	            Toast.makeText(getActivity(), "i:" + i, Toast.LENGTH_SHORT).show();
	        }
	    }
	});

2.toSortedList操作符

	//toSortedList操作符,会将源Observable发送的数据组合为一个List集合,并会按照升序的方式进行排序
	//然后再次在onNext方法中将转换完的List集合进行传递
	Observable.just(40, 10, 80, 30).toSortedList().subscribe(new Action1<List<Integer>>() {
	@Override
	public void call(List<Integer> numList) {
	    for (Integer i : numList) {
	        Toast.makeText(getActivity(), "i:" + i, Toast.LENGTH_SHORT).show();
	    }
	}
	});

3.toMap操作符

	//toMap操作符,将源Observable发送的数据作为Map集合中的值,需要值进行键的定义
	//将转换完毕的Map集合在onNext方法中进行发送
	Observable.just("Alex","Payne").toMap(new Func1<String, Integer>() {
	    @Override
	    public Integer call(String s) {
	        return s.equals("Alex")?0:1;
	    }
	}).subscribe(new Action1<Map<Integer, String>>() {
	    @Override
	    public void call(Map<Integer, String> convertMap) {
	        for (int i = 0; i < convertMap.size(); i++) {
	            Toast.makeText(getActivity(), convertMap.get(i), Toast.LENGTH_SHORT).show();
	        }
	    }
	});

你可能感兴趣的:(rxjava)