gpt4 book ai didi

java - 如何从 Retrofit 异步返回任何对象(无法调用 enqueue() 方法)

转载 作者:行者123 更新时间:2023-12-01 17:29:10 25 4
gpt4 key购买 nike

我想使用 RxJava 从 Retrofit(异步调用)返回 GetCheapestResponseType 对象:

这是我的方法:

public Single<GetCheapestResponseType> getCheapest(...) {

...

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(urlGetCheapest)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();

Controller controller = retrofit.create(Controller.class);

Call<GetCheapestResponseType> callAsync = controller.getCheapest(...);

callAsync.enqueue(new Callback<GetCheapestResponseType>() {
@SneakyThrows
@Override
public void onResponse(Call<GetCheapestResponseType> call, Response<GetCheapestResponseType> response) {
...
// return GetCheapestResponseType; ??
}

@Override
public void onFailure(Call<GetCheapestResponseType> call, Throwable throwable) {
// return throwable; ??
}
});
}

所以我制作了GetCheapestCallbacks接口(interface):

public interface GetCheapestCallbacks {

void onSuccess(@NonNull String result);

void onError(@NonNull Throwable result);
}

我已将其作为参数添加到 getCheapest(..., @Nullable GetCheapestCallbackscallbacks)) 方法

和我添加的onResponse()方法:

calbacks.onSuccess(...);

和我添加的onFailure()方法:

callbacks.onError(throwable);

在 Controller 界面中我有:

public interface Controller {

@GET("oneWayFares")
public Single<GetCheapestResponseType> getCheapest(...);

}

我改变了:

Call<GetCheapestResponseType> callAsync = controller.getCheapest(...);

对于:

Single<GetCheapestResponseType> callAsync = controller.getCheapest(...);

现在我无法对其调用 enqueue() 方法。

如何让它发挥作用?

最佳答案

以前您的返回类型是 Call<> 。 Call 类是为您提供 enqueue() 的类。方法来执行 api 调用。既然你现在返回Single<>这是有道理的enqueue()不再是一个选择。

自从 LiveData 出现以来,我就很少使用 RxJava 了。但据我所知,API 调用在您订阅 Single 后立即执行。换句话说:只调用getCheapest()只要您没有订阅者附加到此Single,就不执行任何操作

所以像这样的东西应该有效:

controller.getCheapest(...).observeOn(AndroidSchedulers.mainThread()).subscribe(
// implement success and error methods
)

编辑:我强烈推荐阅读 Christopher Arriola 和 Angus Huang 所著的《Android 上的响应式编程》。它的结构非常好,对我理解响应式框架的概念有很大帮助。

关于java - 如何从 Retrofit 异步返回任何对象(无法调用 enqueue() 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61156593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com