Using RxJava and Okhttp

前端 未结 5 1897
情书的邮戳
情书的邮戳 2020-12-14 17:15

I want to request to a url using okhttp in another thread (like IO thread) and get Response in the Android main thread, But I don\'t know how to create an

5条回答
  •  被撕碎了的回忆
    2020-12-14 17:22

    It's easier and safer to use Observable.defer() instead of Observable.create():

    final OkHttpClient client = new OkHttpClient();
    Observable.defer(new Func0>() {
        @Override public Observable call() {
            try {
                Response response = client.newCall(new Request.Builder().url("your url").build()).execute();
                return Observable.just(response);
            } catch (IOException e) {
                return Observable.error(e);
            }
        }
    });
    

    That way unsubscription and backpressure are handled for you. Here's a great post by Dan Lew about create() and defer().

    If you wished to go the Observable.create() route then it should look more like in this library with isUnsubscribed() calls sprinkled everywhere. And I believe this still doesn't handle backpressure.

提交回复
热议问题