【问题标题】:Can we use Retrofit, RxJava, RxAndroid together?我们可以一起使用 Retrofit、RxJava、RxAndroid 吗?
【发布时间】:2016-12-22 04:34:02
【问题描述】:

我用过:

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 为我工作?

【问题讨论】:

  • 根据我的经验,我认为将这 3 个一起使用是非常有效和好的。如果我们将 Retrofit 与 RX 一起使用,API 集成会更有效。

标签: android retrofit rx-java rx-android


【解决方案1】:

是的,你可以。

你应该在你的 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);
                        });

【讨论】:

    【解决方案2】:

    是的,您可以一起使用,而且效果更好。 Rxjava with retrofit

    【讨论】:

      【解决方案3】:

      是的,你可以。

      这里是link 用于将 Rxjava 与改造集成的最小示例代码。

      如果您在理解或设置方面遇到任何问题,请告诉我。

      继续学习

      【讨论】:

        【解决方案4】:

        如果您有简单的休息服务调用并且不需要转换,那么仅使用 Retrofit 就足够了。您可以在后台线程上运行改造服务调用,并在主线程上使用响应更新 UI。但问题是您需要注意防止内存泄漏。您需要确保在销毁活动时所有对象都被销毁,以防止内存泄漏。

        但是对于特定的工作流程,如果您需要进行多个服务调用或过滤或转换响应,那么 Retrofit 和 RxJava2 将是正确的选择。 RxJava 使用 CompositeDisposable 可以轻松防止内存泄漏。

        如果您想构建响应式应用程序,而不考虑其余服务调用的复杂性,请选择 RxJava2。

        【讨论】:

          猜你喜欢
          • 2020-01-02
          • 2017-12-05
          • 2023-03-15
          • 1970-01-01
          • 2017-05-09
          • 2015-11-21
          • 1970-01-01
          • 2019-05-27
          • 2012-04-25
          相关资源
          最近更新 更多