我用过:
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
本身是否工作于工作线程?
我是否必须一起使用rxJava
和retrofit
或仅retrofit
为我工作?
答案 0 :(得分:2)
是的,你可以。
您应该在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'
...
}
清单中的权限:
<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);
});
答案 1 :(得分:0)
答案 2 :(得分:0)
答案 3 :(得分:0)
如果你有简单的休息服务电话并且不需要转换,那么仅使用Retrofit就足够了。您可以在后台线程上运行改进服务调用,并在主线程上使用响应更新UI。但问题是你需要注意防止内存泄漏。您需要确保在销毁活动时销毁所有对象以防止内存泄漏。
但是对于特定的工作流程,如果您需要进行多个服务调用或过滤或转换响应,那么Retrofit和RxJava2将是正确的选择。使用CompositeDisposable,RxJava可以轻松防止内存泄漏。
如果您想构建反应式应用程序,无论其他服务调用的复杂性如何,请转到RxJava2。