First, let's take a look at the general usage of retrofit, and in the case of not using Rxjava, we return call by default.
Public interface Serviceapi {//download file @getcall<responsebody> downloadpicfromnet (@Url String fileUrl);}
But if we want to work with Rxjava, we need to redefine our approach in the following ways:
@GETObservable <ResponseBody> downloadpicfromnet (@Url String fileUrl);
returns a observable, the method name is very intuitive is to download the picture from the network parameter is the URL path of the picture
To complete the definition of the request interface, we then create the retrofit object
Retrofit Retrofit = new Retrofit.builder (). BASEURL (Base_url). Addcalladapterfactory (rxjavacalladapterfactory.create ())//Add Rxjava.addconverterfactory (Gsonconverterfactory.create ())//<span style= "font-family:arial, Helvetica, Sans-serif; " > Define the converter to return the result in a JSON format </span>.build ();
Next we create an instance of the SERVICEAPI that we just defined, creating the retrofit created above
Serviceapi Serviceapi = retrofit.create (Serviceapi.class);
OK, now we can use SERVICEAPI to call the Downloadpicfromnet method we just defined to download a picture, you can feel free to Baidu a picture, copy the image address to do the test.
serviceapi.downloadpicfromnet ("http://pic41.nipic.com/ 20140509/4746986_145156378323_2.jpg "). Subscribeon (Schedulers.newthread ())//Implement the method in a new thread. Map (New func1< Responsebody, bitmap> () {@Overridepublic Bitmap call (Responsebody arg0) {if (Savefiletodisc (arg0)) {//Save picture successfully Bitmap Bitmap = Bitmapfactory.decodefile (Getexternalfilesdir (NULL) + File.separator + "baidu.png"); return bitmap;// Returns a Bitmap object}return null;}}). Observeon (Androidschedulers.mainthread ())//is displayed in the Android main thread. Subscribe (new subscriber<bitmap> () { ProgressDialog dialog = new ProgressDialog (mainactivity.this), @Overridepublic void OnStart () {dialog.show (); Super.onstart ();} @Overridepublic void oncompleted () {Dialog.dismiss ();} @Overridepublic void OnError (Throwable arg0) {log.d (TAG, "OnError =====" + arg0.tostring ());} @Overridepublic void OnNext (Bitmap arg0) {imageiv.setimagebitmap (arg0);}});
The example above implements a process of downloading, saving, and showing that the code is very concise and does not have many callbacks compared to the traditional asynctask. Of course, in the actual use can also encapsulate a layer, the creation of retrofit and SERVICEAPI in a Serviceapiimpl implementation class.
Retrofit Rxjava to download, save and display images