0

我正在尝试将 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”。

4

1 回答 1

1

即使 Retrofit 服务具有返回类型Flowable<String>,调用testReactive()也只会在 Android 设备上进行一次 HTTP 调用。

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

这就是改造的工作原理。

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

于 2020-04-10T10:06:42.637 回答