RxAndroid间隔API调用。有没有更好的办法?

时间:2017-03-07 17:45:47

标签: android rx-android

我每隔3秒进行一次天气API调用,并使用showWeather将结果附加到textView("天气"),但我相信有更好的方法可以做到这一点。我不确定为什么我需要创建类Func1但是因为map需要它。还有办法缩短观察者吗?不幸的是,我没有使用lamda。有什么建议吗?

            Observer myObserver = new Observer<String>() {

                @Override
                public void onError(Throwable e) {
                    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
                }

                @Override
                public void onComplete() {

                }

                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String value) {
                    showWeather(value);
                }
            };

            class Func1<T, T1> implements io.reactivex.functions.Function<Long, String > {
                @Override
                public String apply(Long aLong) throws Exception {
                    return getJSON("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1",300);
                }
            }

            Observable.interval(3, TimeUnit.SECONDS)
                    .map(new Func1<Long, Observable<String>>() {
                    }).observeOn(AndroidSchedulers.mainThread()).subscribe(myObserver);

我试过了:

Observable
          .interval(3, SECONDS)
          .subscribeOn(Schedulers.io())
          .fromCallable(new Callable<String>() {
              @Override
              public String call() throws Exception {
                  return getJSON("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1", 300);
              }
           })
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(myObserver)

但我明白了:

03-07 21:47:25.982 21181-21181 / com.alex.rxandroidexamples E / imerExampleFragment $ 1 $ 1:null                                                                                      android.os.NetworkOnMainThreadException                                                                                          在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)

另外如何取消订阅onPause或onPause?

1 个答案:

答案 0 :(得分:1)

我发现最好的方法是:

private final CompositeDisposable disposables = new CompositeDisposable();

Observable fetchWeatherInterval = Observable.interval(3, TimeUnit.SECONDS)
        .map(new Function<Long, String>() {
            @Override
            public String apply(Long aLong) throws Exception {
                return getWeather("http://samples.openweathermap.org/data/2.5/weather?", "London,uk", "b1b15e88fa797225412429c1c50c122a1");
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());

Observer displayWeatherInterval = new Observer<String>() {

    @Override
    public void onError(Throwable e) {
        Log.e("Throwable ERROR", e.getMessage());
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onSubscribe(Disposable d) {
        disposables.add(d);
    }

    @Override
    public void onNext(String value) {
        textViewWeatherInterval.append(value);
    }
};

buttonFetchIntervalWeather.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            fetchWeatherInterval.subscribe(displayWeatherInterval);
        }
    });