您的位置:首页 > 编程语言 > Java开发

简单地使用下RxJava + Retrofit

2015-12-09 16:13 309 查看

RxJava +Retrofit—–仅供参考,后果自负

好多资料,好多的栗子

https://github.com/lzyzsd/Awesome-RxJava

https://github.com/androidmalin/RengwuxianRxjava

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0915/3460.html

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/1130/3736.html?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io

加依赖

在项目的根目录的build.gradle里加

[code]apply plugin: 'me.tatarka.retrolambda'


app的build.gradle里加

[code]    apply plugin: 'me.tatarka.retrolambda'
    buildscript {
        repositories {
            jcenter()
        }

        dependencies {
            classpath 'me.tatarka:gradle-retrolambda:2.5.0'
        }
    }   

    compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
    compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
    compile 'io.reactivex:rxandroid:1.0.1'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
    compile 'com.trello:rxlifecycle:0.3.1'
    compile 'com.trello:rxlifecycle-components:0.3.1'


使用

ApiManger

[code]public class ApiManger {
    private ApiService apiService;
    private Retrofit retrofit;
    private static ApiManger apiManger;

    private ApiManger() {
    }
      public static ApiManger getInstance() {
        if (apiManger == null) {
            apiManger = new ApiManger();
        }
        return apiManger;
    }

    //服务器返回的数据为json的话可以这样写

    public ApiService getService() {
        if (retrofit == null) {
            Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            retrofit = new Retrofit
                    .Builder().baseUrl(BASIC_URL) //你自己需要的网址,如:XXXXXX/
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        if (apiService == null) {
            apiService = retrofit.create(ApiService.class);
        }
        return apiService;
    }

    //如果为String的话

      public ApiService getStrService() {
        if (retrofit == null) {
            retrofit = new Retrofit
                    .Builder()
                    .baseUrl(endpoint)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverter(String.class, new stringConverter())
                    .build();
        }
        if (service == null) {
            service = retrofit.create(ApiService.class);
        }

        return service;
    }

     static class stringConverter implements Converter {

        @Override
        public Object fromBody(ResponseBody body) throws IOException {
            InputStream reader = null;
            try {
                reader = body.byteStream();
                ByteArrayOutputStream writer = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 2];
                int size = -1;
                while ((size = reader.read(buffer)) > 0) {
                    writer.write(buffer, 0, size);
                }
                String result = new String(writer.toByteArray());
                return result;
            } finally {
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public RequestBody toBody(Object value) {
            return null;
        }
    }

    //注意"/" 最好在上面的  baseUrl里面加 
    public interface ApiService {
        @FormUrlEncoded
        @POST("XXXXXXXX")
            Observable<String> search(
            @Field("code") code, 
            @Field("q") String keyword);
    }


MainActivity

[code]public class MainActivity extends RxAppCompatActivity {
    @Bind(R.id.edt)
    EditText edt;
    @Bind(R.id.tv)
    TextView tv;
    private ApiManger apiManger;
    private String allName = "";
    private Subscription subscription;
    private static final String TAG = "-->>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        apiManger = ApiManger.getInstance();
        RxTextView.textChanges(edt)
                .doOnUnsubscribe(() -> Log.e("-->>", "doOnUnsubscribe"))
                .filter(charSequence -> {
                    tv.setText("");
                    return charSequence.length() > 0;
                })
                .switchMap(charSequence -> {
                    return apiManger.getService()
                        .searchProduct("1", charSequence.toString());
                })
                //绑定生命周期.完成后取消订阅
                .compose(this.<String>bindToLifecycle())
                //这个一看就知道了
//              .compose(bindUntilEvent(ActivityEvent.PAUSE))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> tv.setText(s), t -> {
                    Log.e("-->>", "获取数据异常" + t.toString());
                });
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: