android - RxJava使用from操作符之后怎么每次发射数据时延迟一段时间
高洛峰
高洛峰 2017-04-17 18:00:49
0
3
502

为了使用RxJava实现在ImageView中每隔指定时间加载一张系统图片的效果,

Observable.from(getUri()).timer(2,TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(uri
-> {
            Log.e("uri",uri+"");
            Glide.with(this).load(uri).into(img);}); 
            }

在getUri()中返回了一个ArrayList<Uri>对象,然后每次发射一个uri到订阅者中,怎么让这个发射过程延迟调用。
使用timer操作符出现了以下错误:Unknown type class java.lang.Long. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
Peter_Zhu

This error seems to be caused by your Glide and has nothing to do with Timer!

timer is a delayed emission function, which is only executed once. If you want to send data regularly, try the interval function:

Observable.interval(2, TimeUnit.SECONDS)
                  .map(new Func1<Long, String>() {
                      @Override
                      public String call(Long aLong) {
                          return getUrl();
                      }
                  })
                  .subscribe(new Subscriber<String>() {
                      @Override
                      public void onCompleted() {

                      }

                      @Override
                      public void onError(Throwable e) {

                      }

                      @Override
                      public void onNext(String o) {
                          Log.d("xxx interval with func", o);
                      }
                  });
迷茫

For scheduled tasks, you must start from the interval. Don’t always think about starting from the data

public void loop() {
    final List<String> images = getUri();//图片列表
    Observable.interval(0, 2, TimeUnit.SECONDS)//每2秒执行1次,第一次立即执行
              .map(i -> images.get(i.intValue() % images.size()))//把循环次数变成图片路径
              .subscribe(uri -> Glide.with(ctx).load(uri).into(img));//调用Glide
    }

The author’s mistake is that timer is a static method, and the previous from(getUri()) has no effect at all. What is sent is not the image address, but the number of cycles. The type is Long. After throwing it to Glide, the type is wrong.

左手右手慢动作

Just follow a delay after starting from. The specific API is as follows http://reactivex.io/RxJava/javadoc/rx/Observable.html#delay(rx.functions.Func1)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template