search

Home  >  Q&A  >  body text

android - RxJava使用from操作符之后怎么每次发射数据时延迟一段时间

为了使用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

高洛峰高洛峰2887 days ago503

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 18:02:49

    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);
                          }
                      });

    reply
    0
  • 迷茫

    迷茫2017-04-17 18:02:49

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 18:02:49

    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)

    reply
    0
  • Cancelreply