是的,你可以。在清單
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'
...
}
權限:
你應該在你的gradle產出添加此依賴
<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("[email protected]")
.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);
});
我認爲一起使用這3個是非常有效的,從我的經驗很好。如果我們將RX與Retrofit一起使用,則Api集成更有效。 – Nivedh