Rxjava and Volley Requests



我的问题听起来应该有点愚蠢,但我只是从Asynktask跳到RxJava。所以:

是否可以使用RxJava Observable with Volley Requests?它的意思是,使用未来的请求。

我问这个,因为另一个httpClient像改造使用RxJava非常好,但我个人喜欢Volley,所以这是可能的吗?

编辑

根据第一个答案,我知道这是可能的。

你能分享一下吗有什么例子可以说明怎么做吗?

此代码适用于此库

api 'com.netflix.rxjava:rxjava-android:0.16.1'

最后,感谢你的回答,我找到了一个解决方案,想分享:

在我的情况下,我使用活动,但对于片段应该或多或少相等。

我想在响应中得到一个JsonObject,但可以是你的自定义Volley实现。

 public class MyActivity extends BaseActivityWithoutReloadCustomer implements Observer<JSONObject>
{
private CompositeSubscription mCompositeSubscription = new CompositeSubscription();
private Activity act;
 /**
 * @use handle response from future request, in my case JsonObject.
 */
 private JSONObject getRouteData() throws ExecutionException, InterruptedException {
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    String Url=Tools.Get_Domain(act.getApplicationContext(), Global_vars.domain)+ PilotoWs.wsgetRoutesbyUser+ Uri.encode(routeId);
    final Request.Priority priority= Request.Priority.IMMEDIATE;
    Estratek_JSONObjectRequest req= new Estratek_JSONObjectRequest(Request.Method.GET, Url,future,future,act,priority);
    POStreet_controller.getInstance().addToRequestQueue(req);
    return future.get();
}
 /**
 *@use the observable, same type data Jsob Object
 */
 public Observable<JSONObject> newGetRouteData() {
    return Observable.defer(new Func0<Observable<JSONObject>>() {
        @Override
        public Observable<JSONObject> call() {
            Exception exception;
            try {
                return Observable.just(getRouteData());
            } catch (InterruptedException | ExecutionException e) {
                Log.e("routes", e.getMessage());
                return Observable.error(e);
            }
        }
    });
};
@Override
public void onCreate(Bundle instance) {
    super.onCreate(instance);
    setContentView(R.layout.yourLayout);
    act = this;
    /**
     * @condition: RxJava future request with volley
     */
     mCompositeSubscription.add(newGetRouteData()
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(this));
 }

@Override
public void onCompleted() {
    System.out.println("Completed!");
}
@Override
public void onError(Throwable e) {
    VolleyError cause = (VolleyError) e.getCause();
    String s = new String(cause.networkResponse.data, Charset.forName("UTF-8"));
    Log.e("adf", s);
    Log.e("adf", cause.toString());
}
@Override
public void onNext(JSONObject json) {
    Log.d("ruta", json.toString());
}

对我来说,它只是工作。希望能帮助一些人。

编辑 Estratek_JSONObjectRequest.java

public class Estratek_JSONObjectRequest extends JsonObjectRequest{
Activity Act;
Priority priority;
public Estratek_JSONObjectRequest(int method, String url,
                                  JSONObject jsonRequest, Listener<JSONObject> listener,
                                  ErrorListener errorListener,Activity act, Priority p) {
    super(method, url, jsonRequest, listener, errorListener);
    this.Act=act;
    this.priority=p;
}
public Estratek_JSONObjectRequest(int method, String url,
                                  Listener<JSONObject> listener,
                                  ErrorListener errorListener,Activity act, Priority p) {
    super(method, url, null, listener, errorListener);
    this.Act=act;
    this.priority=p;
}
@Override
public Map<String, String> getHeaders()  {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    headers.put("Authorization", "Bearer "+Tools.mySomeBearerToken);
    return headers;
}
//it make posible send parameters into the body.
@Override
public Priority getPriority(){
    return priority;
}
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String je = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        if (je.equals("null")){
            je="{useInventAverage:0}";
            return Response.success(new JSONObject(je), HttpHeaderParser.parseCacheHeaders(response));
        }
        else
            return Response.success(new JSONObject(je), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException var3) {
        return Response.error(new ParseError(var3));
    } catch (JSONException var4) {
        return Response.error(new ParseError(var4));
    }
}

}

这就像Volley构造函数,但我做了自己的自定义,发送一些头,如承载令牌,内容类型,发送优先级等。

对于RXJAVA2库,是这样的:

>。Gradle应该有这样的内容:

api"io.reactivex.rxjava2: rxandroid: 2.0.2":

public class MainActivity extends AppCompatActivity {
CompositeDisposable         mCompositeDisposable = new CompositeDisposable();
@Override
public void onCreate(Bundle instancia) {
    super.onCreate(instancia);
    setContentView(R.layout.sale_orders_list);
    // disposable that will be used to subscribe
    DisposableSubscriber<JSONObject> d = new DisposableSubscriber<JSONObject>() {
        @Override
        public void onNext(JSONObject jsonObject) {
            onResponseVolley(jsonObject);
        }
        @Override
        public void onError(Throwable t) {
            // todo
        }
        @Override
        public void onComplete() {
            System.out.println("Success!");
        }
    };
    newGetRouteData()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(d);
}
@Override
public void onDestroy(){
    super.onDestroy();
    /**
     * @use: unSubscribe to Get Routes
     */
    if (mCompositeDisposable != null){
        mCompositeDisposable.clear();
    }
}

/**
 * @condition: RxJava future request with volley
 */
private JSONObject getRouteData() throws ExecutionException, InterruptedException,RuntimeException {
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    String Url = "https//miapirest.com/api";
    JSONObjectRequest req= new JSONObjectRequest(Request.Method.GET, Url,future,future,act,priority);

    VolleyInstance.addToRequestQueue(req);
    return future.get();
}
/**
 * @condition: this function create a new Observable object and return that if success or
 */
public Flowable<JSONObject> newGetRouteData() {
    return Flowable.defer(new Callable<Publisher<? extends JSONObject>>() {
        @Override
        public Publisher<? extends JSONObject> call() throws Exception {
            return Flowable.just(getRouteData());
        }
    });
};

}

好消息是,先生将Google Volley修改为RxVolley,删除了对HttpClient和RxJava的支持。

RxVolley = Volley + RxJava + OkHttp

完整的文档可在http://rxvolley.mydoc.io/找到

p。史:我目前正在考虑如何使用RxVolley支持多个自定义JSON转换器,如retrofit!

相关内容

  • 没有找到相关文章

最新更新