The source of this article: Tamic
Wen/http://blog.csdn.net/sk719887916/article/details/52132106
Rxjava +rterofit need to master a few skills
Rxjava Introduction and details please visit the more famous "Rxjava detailed", here continue to some of the previous column of the introduction of some easy to ignore skills.
Retrofit+rxjava Combination series Please read:
- Retrofit 2.0
Ultra-practical, perfect support for HTTPS transmission
-
Retrofit2.0
Perfect sync cookie for free login
-
Retrofit 2.0 Super Practice (iii), easy to implement file/image upload
-
-retrofit 2.0 Super Practice (four), complete large file breakpoint download
-
Ultra-good Retrofitclient tool class based on the Retrofit2.0 package
-
Play the IOC and teach you to implement your custom retrofit framework with bare hands
-
How to gracefully cancel a Rxjava request
Cancel Subscription
In general we can unsubscribe directly after the view dies without Rxjava.
if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } observable.unsubscribeOn(Schedulers.io());
Can be invoked in the activity's onDestroy(), fragment onDestroyView()
There is also a scenario is the use of Rxjava request network data, need to save data after the network and update the UI, this situation is doomed to cause Rxjava error, resulting in app Flash, which we can determine whether the previous Activity/view is empty, and whether it has been showing If
Neither exists, so you don't need to update the UI. Only the saved data can be processed.
Subscription issues
Scenarios that require the UI to be drawn and then subscribed to prevent blocking the UI, we need to defer subscription execution.
Subscribe now;
observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(action);
Deferred subscription
observable.delay(2, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(action);
Basic Apiservice
Usually we write the interface will have the following definition, add an API must write a method
public interface MyApi {@GET("app.php")Observable<SouguBean> getSougu(@Query("name") String name);@GET("/getWeather")Observable<ResponseBody> getWeather(@QueryMap Map<String, String> maps);}
A lot of times every new interface to write an API, is not a good way to replace this situation.
@GET()<T> Observable<ResponseBody> get( @Url String url, @QueryMap Map<String, T> maps);
We can define a common getapi, the URL is dynamically passed in, return modle defined as Responsebody, and the actual parameters are defined as generics, whether it is changing the URL, or the service side return type, including the number of parameters can be perfectly adapted, this way technology is not in place, do not use, Because retrofit explicitly indicates that the interface must be given a definite type, take it easy!
This can be the case when the upper layer is assembled for General Assembly:
public <T> T get(String url, Map<String, T> maps, BaseSubscriber<ResponseBody> subscriber) {return (T) apiManager.get(url, maps).compose(schedulersTransformer).compose(handleErrTransformer()).subscribe(subscriber);}
Can't you read it? Do not understand is not strange, the source can go to the end of the article download research, here is just a list. This approach is well suited for migrating from httpclent to retrofit to bring about interface adaptation issues, one with a quasi ...
Basic Subscriber
Many times we need to borrow Rxjava to open a number of observable to read the network, this is our different subscriber processing more trouble, so unified to the Subscriber on the network to return to the processing and, there is no network to judge, Can even show loading progress on demand, etc.
Constructs abstract Basesubscribe class, only handles and start() onCompleted() , upper processing only handles onError() andonNext()
/** * Basesubscriber * Created by tamic on 2016-7-15. */PublicAbstract class basesubscriber<t> extends subscriber<t > { PrivateBaseactivity context; Public Basesubscriber (baseactivity context) { This. Context = Context; }@Overridepublic void OnStart () {Super. OnStart ();if(! Networkutil.isnetworkavailable (context)) {Toast.maketext (context),"The current network is not available, please check the network conditions", Toast.length_short). Show ();//Be sure to invoke the following sentence actively.OnCompleted ();return; }//Show progress barShowloadingprogress (); }@Overridepublic void oncompleted () {//Close wait progress barCloseloadingprogress (); } }
This way we only care about success and failure at the top of the call, without worrying about the network.
observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BaseSubscriber<ResponseBody>(MainActivity.this) { @Override public void onError(Throwable e) { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } @Override public void onNext(ResponseBody responseBody) { Toast.makeText(MainActivity.this, responseBody.toString(), Toast.LENGTH_LONG).show(); } }); );
If you want to handle error errors uniformly, you can also handle onerror () in Basesubscriber, and then on the upper callback, look at your project situation.
/** * 网络返回基类 支持泛型 * Created by Tamic on 2016-06-06. */public class BaseResponse<T> { private int code; private String msg; private T data; public int getCode() { return code; }public void setCode(int code) { this.code = code;}public String getMsg() { return msg;}public void setMsg(String msg) { this.msg = msg;}public T getData() { return data;}public void setData(T data) { this.data = data;}public boolean isOk() { return code == 0;}}
If successful results are processed, you can add resonsebody to generics.
Response generally contains code,msg, data, where you can intermediate judgment code to carry out business distribution, the code is very simple to see the end of the article source can if you feel the current return to judge trouble, you can also define the Respons base class.
In OnNext () we only need to determine the status code uniformly
@Override public void onNext(BaseResponse<IpResult> responseBody) { if (responseBody.isOk()) { IpResult ip = responseBody.getData(); Toast.makeText(MainActivity.this, ip.toString(), Toast.LENGTH_LONG).show(); }}
Error result problem
The original package conversion is carried out via Rx's Func1 Throwable
We will turn the original Throwable strong into a custom responethrowable;
private static class HttpResponseFunc《T》 implements Func1《Throwable, Observable《T》》 { @Override public Observable<T> call(Throwable t) { return Observable.error(ExceptionHandle.handleException(t)); }}
responethrowable
public static class ResponeThrowable extends Exception { public int code; public String message; public ResponeThrowable(Throwable throwable, int code) { super(throwable); this.code = code; }}
We have dealt with the strong transfer of work Func1 and continue to add to Observable the middle:
So the onerrorresumenext provided with observable can associate your custom with the Func1 error handling class:
((Observable) observable).onErrorResumeNext(new HttpResponseFunc<T>());
It's possible that you're feeling a little bit out of it, this premise you need to know about Rxjava's escape character and Observable.Transformer
And alsoFunc1
In this way, we handle the error status returned by the server, and then we can get the language that the user understands with a little translation.
This class I refer to the case of skiff classmate, I made the improvement again:
Exceptionhandle Error Handling Driver
public class Exceptionhandle {private static final int unauthorized = 401; private static final int FORBIDDEN = 403; priv ATE static final int not_found = 404; private static final int request_timeout = 408; private static final int internal_server_error = 500; private static final int bad_gateway = 502; private static final int service_unavailable = 503; private static final int gateway_timeout = 504; public static responethrowable HandleException (Throwable e) {responethrowable ex; if (e instanceof httpexception) {HttpException HttpException = (httpexception) e; ex = new Responethrowable (E, ERROR. HTTP_ERROR); Switch (Httpexception.code ()) {case Unauthorized:case forbidden:case not_found: Case Request_timeout:case Gateway_timeout:case internal_server_error:case Bad_gat Eway:case SERVICE_UNAVAILABLE:default:ex.message = "Network error"; Break } return ex; } else if (e instanceof serverexception) {serverexception resultexception = (serverexception) e; ex = new Responethrowable (resultexception, Resultexception.code); Ex.message = Resultexception.message; return ex; } else if (e instanceof jsonparseexception | | e instanceof jsonexception | | e instanceof parseexcept ION) {ex = new responethrowable (E, ERROR. PARSE_ERROR); Ex.message = "Parse error"; return ex; } else if (e instanceof connectexception) {ex = new responethrowable (e, error.netword_error); Ex.message = "Connection Failed"; return ex; } else if (e instanceof javax.net.ssl.SSLHandshakeException) {ex = new responethrowable (E, ERROR. SSL_ERROR); Ex.message = "Certificate validation failed"; return ex; } else {ex = new responethrowable (E, ERROR. UNKNOWN); Ex.message = "Unknown error"; return ex; }}/** * Convention Exception */class Error {/** * unknown errors */public static final int UNKNOWN = 1000; /** * Parse Error */public static final int parse_error = 1001; /** * Network error */public static final int netword_error = 1002; /** * protocol error */public static final int http_error = 1003; /** * Certificate Error */public static final int ssl_error = 1005;} public static class Responethrowable extends Exception {public int code; public String message; Public responethrowable (throwable throwable, int code) {super (throwable); This.code = code; }}public class Serverexception extends runtimeexception {public int code; public String message;
}
You can then handle the exception pull in the Basesubscriber
public abstract class BaseSubscriber<T> extends Subscriber<T> {private Context context;public BaseSubscriber(Context context) { this.context = context;}@Overridepublic void onError(Throwable e) { Log.e("Tamic", e.getMessage()); // todo error somthing if(e instanceof ExceptionHandle.ResponeThrowable){ onError((ExceptionHandle.ResponeThrowable)e); } else { onError(new ExceptionHandle.ResponeThrowable(e, ExceptionHandle.ERROR.UNKNOWN)); } }}
This is how the last top call goes:
Retrofitclient.getinstance (mainactivity.this). Createbaseapi (). GetData (New Basesubscriber (mainactivity.this) {
@Override public void onError(ResponeThrowable e) { // 处理翻译后异常。 Log.e("Tamic", e.code + " "+ e.message); Toast.makeText(MainActivity.this, e.message, Toast.LENGTH_LONG).show(); } @Override public void onNext(IpResult responseBody) { Toast.makeText(MainActivity.this, responseBody.toString(), Toast.LENGTH_LONG).show(); } }, "21.22.11.33");
Caching issues
Sometimes there is a need to increase the cache function when there is no network, so add the base interceptor to retrofit to handle the caching problem
/** * baseinterceptor * Created by tamic on 2016-7-15. */ Public class baseinterceptor implements Interceptor{ PrivateMap<string, string> headers;PrivateContext context; Public Baseinterceptor(Map<string, String> headers, context context) { This. headers = headers; This. Context = Context; }@Override PublicResponseIntercept(Chain Chain)throwsIOException {Request.builder Builder = Chain.request (). Newbuilder (); Builder.cachecontrol (cachecontrol.force_cache). URL (chain.request (). URL ()). build ();if(! Networkutil.isnetworkavailable (context)) {(Activity) context). Runonuithread (NewRunnable () {@Override Public void Run() {Toast.maketext (context,"No network at this moment!", Toast.length_short). Show (); } }); }if(Headers! =NULL&& headers.size () >0) {set<string> keys = Headers.keyset (); for(String Headerkey:keys) {Builder.addheader (Headerkey, Headers.get (Headerkey)). Build (); } }if(networkutil.isnetworkavailable (context)) {intMaxAge = -;//read from cache for SBuilder. Removeheader ("Pragma"). AddHeader ("Cache-control","public, max-age="+ maxAge). Build (); }Else{intMaxstale = -* -* -* -;//tolerate 2-weeks staleBuilder. Removeheader ("Pragma"). AddHeader ("Cache-control","Public, only-if-cached, max-stale="+ Maxstale). Build (); }returnChain.proceed (Builder.build ()); }}
Okhttpclient Join Interceptor
okHttpClient = new OkHttpClient.Builder() .addInterceptor(new BaseInterceptor(headers, context)) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .build();
Retrofit Join Okhttpclient
retrofit = new Retrofit.Builder() .client(okHttpClient) .baseUrl(url) .build();
If you do not want to use Okhttp's own cache policy, because this requires the server side to handle the cache request header, it will be thrown: HTTP 504 unsatisfiable Request (only-if-cached)
In addition to implementing caching in a way that modifies Request.cachecontrol, you can also customize a Cahe policy to implement local hard caches.
Build Cahemanager, with a URL corresponding to the JSON implementation, this class is very simple, you can implement it yourself, time policy can self-join the extension
In Basesubscriber to make network judgment, load the cached data to return it properly;
@Override public void onStart() { super.onStart(); Toast.makeText(context, "http is start", Toast.LENGTH_SHORT).show(); // todo some common as show loadding and check netWork is NetworkAvailable // if NetworkAvailable no ! must to call onCompleted if (!NetworkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "无网络", Toast.LENGTH_SHORT).show(); if (isNeedCahe) { Toast.makeText(context, "无网络,已智能读取缓存!", Toast.LENGTH_SHORT).show(); IpResult ipResult = new Gson().fromJson(CaheManager.getjson(url), IpResult.class); onNext((T) ipResult); } onCompleted(); }}
General question which comes
1 URL is escaped
http://api.myapi.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist
Please change @path to @url
public interface APIService { @GET Call<Users> getUsers(@Url String url);}
Or:
public interface APIService { @GET("{fullUrl}") Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);}
2Method Method Not found
Java.lang.IllegalArgumentException:Method must not being null
Please specify the specific request type @get @post, etc.
public interface APIService { @GET Call<Users> getUsers(@Url String url);}
3URL encoding is not correct, @fieldMap parameters must is use formurlencoded
If you use Fieldmap plus formurlencoded encoding
@POST()@FormUrlEncodedObservable<ResponseBody> executePost( @FieldMap Map<String, Object> maps);
The upper layer needs a transform to convert its own map to Fieldmap
@FieldMap(encoded = true) Map<String, Object> parameters,
4 paht and URLs used together
Using @Path and @Url paramers together with Retrofit2
Java.lang.IllegalArgumentException: @Path parameters May is used with @Url. (Parameter #4
If you are like this:
@GETCall<DataResponse> getOrder(@Url String url, @Path("id") int id);
Please specify a placeholder in your URL. URL:
www.myAPi.com/{Id}
Summarize
Then the last introduction, the author of the new framework development novate is nearing the end, it is estimated to be able to meet with you this month, please continue to pay attention!
Package : https://github.com/Tamicer/RetrofitClient
Source : Https://github.com/Tamicer/Novate
Rxjava + Retrofit You need to master a few classic tricks