간단한 네트워크 요청을 위한 Retrofit2 + RxAndroid2

요즘 Retrofit2+RxAndroid2가 핫하다고 해서 Retrofit2+RxAndroid2에 대해 간단하게 알아봤습니다.
1: 종속 추가
     compile 'io.reactivex.rxjava2:rxjava:2.0.1'     compile 'io.reactivex.rxjava2:rxandroid:2.0.1'    //compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//retrofit는 현재 rxjava1에만 지원됩니다.XX     compile 'com.squareup.retrofit2:retrofit:2.1.0'     compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'//대신이 쓴 이 라이브러리는 rxjava2.X     compile 'com.squareup.retrofit2:converter-gson:2.1.0'     compile 'com.squareup.okhttp3:okhttp:3.4.1'     compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
2: Retroft 만들기
public class RetrofitManager {

    private static ParentApi mParentApi = null;
    private static String mIp = Constant.ip;
    private static int mHost = Constant.port;

    private RetrofitManager(){}

    private static synchronized Retrofit getRetrofit(){
        // Log     
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);        //loglog       
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(httpLoggingInterceptor);
        //60 
        builder.readTimeout(60000, TimeUnit.MILLISECONDS);      //         
        builder.writeTimeout(60000, TimeUnit.MILLISECONDS);     //         
        builder.connectTimeout(60000, TimeUnit.MILLISECONDS);   //         
        //    cookiesession   
        builder.cookieJar(new CookieJar() {
            private final HashMap, List> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(HttpUrl url, List cookies) {
                cookieStore.put(url, cookies);
            }

            @Override
            public List loadForRequest(HttpUrl url) {
                List cookies = cookieStore.get(url);
                return cookies != null ? cookies : new ArrayList();
            }
        });

        OkHttpClient client = builder.build();

        return new Retrofit.Builder()
                .client(client)
                .baseUrl(String.format(Api.baseUrl, Constant.ip, Constant.port))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized ParentApi getApi(){
        if(null == mParentApi){
            mParentApi = getRetrofit().create(ParentApi.class);
            return mParentApi;
	//            ,     IP port      
        } else if(!mIp.equals(Constant.ip) || mHost != Constant.port){
            mIp = Constant.ip;
            mHost = Constant.port;
            mParentApi = getRetrofit().create(ParentApi.class);
            return mParentApi;
        }
        return mParentApi;
    }

}

3: 메모 생성
public interface ParentApi {

    /*************************************************SSN**************************************************************/

    @POST("your interface")
    Observable getAllRecorderStates(@Body Map,String> map);

}

4: RxAndroid 사용
Map,String> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
setLoadingState(LOAD_STATE.STATE_LOADING);
Observable observable = RetrofitManager.getApi().getAllRecorderStates(map);
observable.subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                //    
            }

            @Override
            public void onNext(SchoolBean schoolBean) {
                //        
            }

            @Override
            public void onError(Throwable e) {
                setLoadingState(LOAD_STATE.STATE_EMPTY);
            }

            @Override
            public void onComplete() {

            }
        });

좋은 웹페이지 즐겨찾기