我的问题应该听起来像傻瓜,但我只是从 Asynktask跳到RxJava 。 所以:
可以使用RxJava Observable和Volley Requests吗?这意味着, 使用未来的请求。
我问这个,因为像改装这样的另一个httpClient很好地使用了RxJava,但是个人喜欢Volley,它有可能吗?
修改
根据第一个答案,我知道这是可能的。
你能分享吗? 一些样本展示了如何做到这一点?
答案 0 :(得分:13)
此代码与本图书馆相关
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构造函数,但是我自己定制,发送一些标题,如bearer token,content-type,send priority等。 否则是一样的。
对于RXJAVA2图书馆来说,这就是方法:
&GT; build.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());
}
});
};
}
答案 1 :(得分:5)
好消息是Mr.张涛 kymjs将Google排球修改为 RxVolley ,删除了HttpClient和RxJava支持。
提供的完整文档RxVolley = Volley + RxJava + OkHttp
P.S: 我正在考虑如何使用RxVolley支持多种自定义JSON转换器,例如改造!