gpt4 book ai didi

android - 我们可以同时使用 Retrofit、RxJava 和 RxAndroid 吗?

转载 作者:行者123 更新时间:2023-11-29 19:26:35 27 4
gpt4 key购买 nike

我用过:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retrofit
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

我应该这样使用吗,我读过 retrofit 1.x 本身在工作线程上工作?我应该同时使用 rxJavaretrofit 还是只为我工作 retrofit

最佳答案

是的,你可以。

您应该在您的 gradle 中添加此依赖项:

dependencies {
...
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.2.1'
...
}

list 中的权限:

<uses-permission android:name="android.permission.INTERNET" />  

服务创建者可能是这样的:

public class RxServiceCreator {

private OkHttpClient.Builder httpClient;
private static final int DEFAULT_TIMEOUT = 30; //seconds

private Gson gson;
private RxJavaCallAdapterFactory rxAdapter;
private Retrofit.Builder builder;

private static RxServiceCreator mInstance = null;

private RxServiceCreator() {
httpClient = new OkHttpClient.Builder();
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
builder = new Retrofit.Builder()
.baseUrl("yourbaseurl")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(rxAdapter);

if (BuildConfig.REST_DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}

httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}

public static RxServiceCreator getInstance() {
if (mInstance == null) {
mInstance = new RxServiceCreator();
}
return mInstance;
}

public <RESTService> RESTService createService(Class<RESTService> service) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(service);
}
}

你的界面可能是这样的:

public interface UserAPI {

@GET("user/get_by_email")
Observable<Response<UserResponse>> getUserByEmail(@Query("email") String email);
}

最后调用 api:

UserAPI userApi = RxServiceCreator.getInstance().createService(UserAPI.class);

userApi.getUserByEmail("user@example.com")
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userResponse -> {
if (userResponse.isSuccessful()) {
Log.i(TAG, userResponse.toString());
} else {
Log.i(TAG, "Response Error!!!");
}
},
throwable -> {
Log.e(TAG, throwable.getMessage(), throwable);
});

关于android - 我们可以同时使用 Retrofit、RxJava 和 RxAndroid 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41275856/

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