Can we use Retrofit, RxJava, RxAndroid together?

2019-06-05 06:58发布

I have used:

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'

Should i use like this way, i read retrofit 1.x itself work on worker thread? Should i have to use rxJava and retrofit together or just retrofit work for me?

4条回答
何必那么认真
2楼-- · 2019-06-05 07:47

yes you can use together and also better. Rxjava with retrofit

查看更多
Explosion°爆炸
3楼-- · 2019-06-05 07:50

Yes you can.

You should add this dependencies in your 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'
   ...
}

Permission in manifest:

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

A service creator could be like this:

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);
    }
}

You interface could be some like this:

public interface UserAPI {

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

And finally to make an api call:

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);
                        });
查看更多
Evening l夕情丶
4楼-- · 2019-06-05 07:55

Yes, you can.

Here is the link for minimal sample code for integrating Rxjava with retrofit.

Do let me know if you face any problem understanding or setting it up.

Keep Learning

查看更多
SAY GOODBYE
5楼-- · 2019-06-05 07:55

If you have simple rest service call and no transformation is required, then using just Retrofit would be enough. You can run retrofit service calls on the background thread and update UI with response on main thread. But the problem is that you need to take care of preventing memory leaks. You need to make sure that all objects are destroyed when activity is destroyed to prevent memory leaks.

But for a particular work flow, if you need to make multiple service calls or filter or transform responses, then Retrofit and RxJava2 will be the right option. And preventing memory leaks is easy with RxJava using CompositeDisposable.

If you want to build reactive apps, regardless of complexity of rest service calls, go for RxJava2.

查看更多
登录 后发表回答