RxJava + Retrofit

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RxJava + Retrofit相关的知识,希望对你有一定的参考价值。

 

public class RestApi {
       public static String BASE_URL = "http://202.108.31.64:9080/api/v2.0/";
    
    public static String API_SERVER_ADDR = "ApiServerAddr";
    public static String API_SERVER_PORT = "ApiServerPort";
  
    public static String DEF_SERVER_PORT = "";
    public static String MQTT_BROKER = "tcp://" + DEF_SERVER_ADDR + ":1883";


    private static Retrofit retrofit;
    private static RestService restService;

    public static void init(final Context context){
        //Locale locale = context.getResources().getConfiguration().locale;
        //String language = locale.getLanguage();
        String able= context.getResources().getConfiguration().locale.getCountry();
        if (able.equals("CN") /*language.endsWith("zh")*/){
            DEF_SERVER_ADDR = "www.baidu.cn";
        }else{
            DEF_SERVER_ADDR = "www.baidu.cc";
        }

//        if (retrofit != null) return;

        TokenAuthenticator authenticator = new TokenAuthenticator(context);
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
         final String token = settings.getString(LoginActivity.TOKEN, "no token");
        final String BaseURL = "https://" + settings.getString(API_SERVER_ADDR, DEF_SERVER_ADDR) /*+ ":" + settings.getString(API_SERVER_PORT, DEF_SERVER_PORT)*/ + "/api/v2.0/";
        MQTT_BROKER = "tcp://" + settings.getString(API_SERVER_ADDR, DEF_SERVER_ADDR) + ":1883";
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                                    .addInterceptor(new Interceptor() {
                                        @Override
                                        public Response intercept(Interceptor.Chain chain) throws IOException {
                                            Request original = chain.request();
                                            /*SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
                                            String token = settings.getString(LoginActivity.TOKEN, "no token");*/
                                            // Request customization: add request headers
                                            Request.Builder requestBuilder = original.newBuilder()
                                                    .header("x-login-token", token)
                                                    .method(original.method(), original.body());

                                            Request request = requestBuilder.build();
                                            return chain.proceed(request);
                                        }
                                    })
                                    //.authenticator(authenticator)
                                    .build();


        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BaseURL)
                .client(okHttpClient)
                .build();

        restService = retrofit.create(RestService.class);
    }

    public interface RestService{
        @GET("seriesList")
        Observable<List<Series>> getSeries();

        @GET("projects")
        Observable<ProjectList> getProjects(@Query("offset") int start, @Query("limit") int count);

        @GET("seriesProjects/{slug}")
        Observable<ProjectSeries> getProjectsBySeries(@Path("slug") String slug);

        @GET("projects/{project}/download/{core}")
        Call<ResponseBody> getFirmware(@Path("project") String project, @Path("core") String core);

        @GET
        Call<ResponseBody> getPdf(@Url String pdfUrl);

        @GET("projects/{project}/widgets")
        Observable<WidgetList> getProjectWidgets(@Path("project") String projectID, @Query("token") String token);

        @PUT("projects/{project}/widgets")
        Observable<Result> putProjectWidgets(@Path("project") String projectID, @Body WidgetList widgetList);

        @GET("devices")
        Observable<DeviceList> getDevices(@Query("offset") int start, @Query("limit") int count);

        @GET("pub_devices")
        Observable<DeviceList> getPubDevices(@Query("offset") int start, @Query("limit") int count);

        @GET("devices/{device}")
        Observable<Device> getDevice(@Path("device") String deviceID);

        @DELETE("devices/{device}")
        Observable<ResponseBody> deleteDevice(@Path("device") String deviceID);
        /*@DELETE("devices/{device}/reset_token")
        Observable<ResponseBody> resetTokenDevice(@Path("device") String deviceID);*/

        @GET("devices/{device}/widgets")
        Observable<WidgetList> getDeviceWidgets(@Path("device") String deviceID, @Query("token") String token);

        @PUT("devices/{device}/widgets")
        Observable<Result> putDeviceWidgets(@Path("device") String deviceID, @Body WidgetList widgetList);

        @GET("registsByMac/{mac}")
        Call<List<Device>> getRegisterDevices(@Path("mac") String mac);

        @PUT("regists/{device}")
        Observable<Device> registerDevices(@Path("device") String deviceID, @Body Device device);

        @POST("da/")
        Observable<ResponseBody> postDeviceAction(@Body Map<String, Object> message);

        @POST("dp/")
        Observable<ResponseBody> postDeviceProperty(@Body Map<String, Object> message);

        @PUT("devices/{device}/share")
        Observable<ResponseBody> shareDevice(@Path("device") String deviceID, @Body Map<String, Object> body);

        @PUT("devices/{deviceID}/reset_token")
        Observable<ResponseBody> resetToken(@Path("deviceID") String deviceID, @Body Map<String, Object> body);

        @PUT("devices/{device}")
        Call<ResponseBody>setDeviceAvatar(@Path("device") String deviceID, @Body Device device);

        @PUT("projects/{project}")
        Call<ResponseBody>setProjectAvatar(@Path("project") String projectID, @Body Project project);
    }


    public static void getSeries(Subscriber<List<Series>> subscriber){
        restService.getSeries()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(androidSchedulers.mainThread())
                .subscribe(subscriber);

    }
    public static void getProjects(Subscriber<ProjectList> subscriber, int start, int count){
        restService.getProjects(start, count)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }
    public static void getProjectsBySeries(Subscriber<ProjectSeries> subscriber, String slug){
        restService.getProjectsBySeries(slug)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }

    //后台线程统一管理,同步调用
    public static Call<ResponseBody> getFirmware(String project, String core){
        return restService.getFirmware(project, core);
    }

    public static Call<ResponseBody> getPdf(String path){
        return restService.getPdf(path);
    }

    public static Call<ResponseBody> setProjectAvatar(String projectID, Project project){
        return restService.setProjectAvatar(projectID, project);
    }
    public static Call<ResponseBody> setDeviceAvatar(String deviceID, Device device){
        return restService.setDeviceAvatar(deviceID, device);
    }

    public static void getDevices(Subscriber<DeviceList> subscriber, int start, int count){
        restService.getDevices(start, count)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void getPubDevices(Subscriber<DeviceList> subscriber, int start, int count){
        restService.getPubDevices(start, count)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void getDevice(Subscriber<Device> subscriber, String deviceID){
        restService.getDevice(deviceID)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void deleteDevice(Subscriber<ResponseBody> subscriber, String deviceID){
        restService.deleteDevice(deviceID)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void getDeviceWidgets(Subscriber<WidgetList> subscriber, String deviceID, String token){
        restService.getDeviceWidgets(deviceID, token)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void putDeviceWidgets(Subscriber<Result> subscriber, String deviceID, WidgetList widgetList){
        restService.putDeviceWidgets(deviceID, widgetList)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void getProjectWidgets(Subscriber<WidgetList> subscriber, String deviceID, String token){
        restService.getProjectWidgets(deviceID, token)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void putProjectWidgets(Subscriber<Result> subscriber, String projectID, WidgetList widgetList){
        restService.putProjectWidgets(projectID, widgetList)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static Call<List<Device>> getRegisterDevices(String mac){
        return restService.getRegisterDevices(mac);
    }

    public static void registerDevices(Subscriber<Device> subscriber, String deviceID, Device device){
        restService.registerDevices(deviceID, device)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void shareDevice(Subscriber<ResponseBody> subscriber, String deviceID, long expireAt){
        Map<String, Object> body = new HashMap<>();
        Map<String, Object> control = new HashMap<>();
        control.put("expireAt", expireAt);
        body.put("share", 2);
        body.put("shareControl", control);
        restService.shareDevice(deviceID, body)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void resetToken(Subscriber<ResponseBody> subscriber, String deviceID, String token){
        Map<String, Object> body = new HashMap<>();
        Map<String, Object> control = new HashMap<>();
//        control.put("expireAt", expireAt.getTime());
        body.put("share", 2);
        body.put("shareControl", control);
        body.put("token",token);
        restService.resetToken(deviceID, body)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void postDeviceAction(Subscriber<ResponseBody> subscriber, Map<String, Object> body){
        restService.postDeviceAction(body)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public static void postDeviceProperty(Subscriber<ResponseBody> subscriber, Map<String, Object> body){
        restService.postDeviceProperty(body)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
}

 

以上是关于RxJava + Retrofit的主要内容,如果未能解决你的问题,请参考以下文章

MVP+Retrofit+RxJava+Dagger框架

Android RxJava/RxAndroid结合Retrofit使用

Android--Retrofit+RxJava

使用 RxJava 链接 Retrofit 调用

基于Retrofit+RxJava的Android分层网络请求框架

RxJava/Retrofit - 如何强制用户使用特定的订阅者子类?