【问题标题】:Android Retrofit + Rxjava flowable completes too earlyAndroid Retrofit + Rxjava flowable 过早完成
【发布时间】:2020-04-09 15:55:34
【问题描述】:

我正在尝试将 io.reactivex.Flowable 从 Spring RestController 发送到使用 Retrofit 和 Rxjava 的 Android 应用程序。如果我使用浏览器检查 Rest 端点返回的内容,我会按预期得到一系列值,但在 Android 中我只得到一个值,然后它调用 onComplete 方法。我错过了什么?

弹簧控制器:

@GetMapping("/api/reactive")
    public Flowable<String> reactive() {
        return Flowable.interval(1, TimeUnit.SECONDS).map(sequence -> "\"Flowable-" + LocalTime.now().toString() + "\"");
    }

改造存储库:

@GET("reactive")
    Flowable<String> testReactive();

主要服务:

public useReactive() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Values.BASE_URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        userRepository = retrofit.create(UserRepository.class);

        Flowable<String> reactive = userRepository.testReactive();
        Disposable disp = reactive.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ResourceSubscriber<String>() {
                    @Override
                    public void onNext(String s) {
                        logger.log(Level.INFO, s);
                        Toast.makeText(authActivity, s, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable t) {
                        t.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        logger.log(Level.INFO, "Completed");
                        Toast.makeText(authActivity, "Completed", Toast.LENGTH_SHORT).show();
                    }
                });
    }

在调用 useReactive() 方法时,我只得到一个值“Flowable-...”,然后是“Completed”。

【问题讨论】:

    标签: android spring-boot retrofit2 rx-java2 flowable


    【解决方案1】:

    即使 Retrofit 服务的返回类型为 Flowable&lt;String&gt;,调用 testReactive() 也只会在 Android 设备上进行一次 HTTP 调用。

    Flowable 类型只是为了兼容性,实际上它最终会是一个Flowable,它发出一个值然后终止。

    这就是改造的工作原理。

    如果您想要不断接收从服务器发出的新值,可能需要找到另一个解决方案,可能是GRPC 或轮询服务器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2018-06-12
      • 2011-02-24
      • 2016-01-11
      • 2014-10-31
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多