The Retrofit+okhttp+rxjava cache architecture in Android uses _android

Source: Internet
Author: User

Rxjava how to combine with retrofit
first throw out the contents of the Build.gradle file

dependencies {
  Compile filetree (dir: ' Libs ', include: [' *.jar '])
  testcompile ' junit:junit:4.12 ' compile '
  com.android.support:appcompat-v7:23.2.0 '
  compile ' io.reactivex:rxjava:1.1.0 '
  compile ' Io.reactivex: rxandroid:1.1.0 '
  compile ' com.squareup.retrofit2:retrofit:2.0.0-beta4 '
  compile ' com.squareup.retrofit2: Converter-gson:2.0.0-beta4 '
  compile ' com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4 '
  compile ' com.google.code.gson:gson:2.6.2 '
  compile ' com.jakewharton:butterknife:7.0.1 '
}

In other words, this article is based on RxJava1.1.0 and retrofit 2.0.0-beta4. Adding Rxandroid is due to threading problems in Rxjava.

The following first build a basic page, the page is very simple, first look at the file directory structure

The code for Activity_main.xml is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_ Vertical_margin "tools:context=". Activity. Mainactivity "> <button android:id=" @+id/click_me_bn "android:layout_width=" Match_parent "Android:layo" ut_height= "Wrap_content" android:layout_alignparentbottom= "true" android:padding= "5DP" android:text= "dot Me" a Ndroid:textsize= "16sp"/> <textview android:id= "@+id/result_tv" android:layout_width= "Match_parent" and
    roid:layout_height= "Match_parent" android:layout_above= "@id/click_me_bn" android:text= "Hello World!" Android:textsiZe= "16sp"/> </RelativeLayout>

 

The code for Mainactivity.java is as follows:

Package com.queen.rxjavaretrofitdemo.activity;

Import Android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;
Import Android.widget.Button;
Import Android.widget.TextView;

Import COM.QUEEN.RXJAVARETROFITDEMO.R;

Import Butterknife. Bind;
Import Butterknife. Butterknife;
Import Butterknife. OnClick;

public class Mainactivity extends Appcompatactivity {

  @Bind (r.id.click_me_bn)
  Button clickmebn;
  @Bind (R.ID.RESULT_TV)
  TextView Resulttv;

  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);
    Butterknife.bind (this);
  }

  @OnClick (r.id.click_me_bn) public
  void OnClick () {
    getmovie ();
  }

  The network request
  private void Getmovie () {

  }
}

Be careful not to forget to add network permissions

<uses-permission android:name= "Android.permission.INTERNET"/>

Cache configuration

There are a number of ways to implement offline caching for app network data, such as storing in a database (parsing it when saving JSON use), storing proprietary files, or sharedpreference, etc., or you can implement LRUCache and
Disklrucache These two caching policies constitute level two caching (memory and disk)

Caching is very important for the mobile end:

    • Reduce the number of requests and reduce server pressure.
    • Local data is read faster, leaving the page blank for hundreds of milliseconds.
    • Provide data in the absence of a network.

The okhttp cache design is similar to the browser's cache design, and can be cached by adding a response header.

Retrofit is an android (Java) client implementation that relies on Okhttp's set of restful architectures
By constructing the. Client () method of retrofit, the implementation of the okhttp is changed to achieve the effect of caching, without introducing the specific use of retrofit.

The following is an example of the implementation of a network cache, no network read-only cache

File Cachefile = new file (App.getcontext (). Getexternalcachedir (), "Zhibookcache");
    Cache cache = New cache (CACHEFILE,1024*1024*50); Interceptor Interceptor = new Interceptor () {@Override public Response intercept (Chain Chain) throws Ioexcept
        ion {Request Request = Chain.request (); if (! Httputils.isnetworkconnected (App.getcontext ())) {request = Request.newbuilder (). CacheControl (Cac
        Hecontrol.force_cache). build ();
        } Response Response = chain.proceed (request);
          if (httputils.isnetworkconnected (App.getcontext ())) {int maxage = 0 * 60;
              Set Cache timeout 0 hours response.newbuilder () when there is a network. Header ("Cache-control", "public, max-age=" + maxage)
        . Removeheader ("Pragma")/clear header information, because if the server does not support, it will return some interference information, do not clear the following cannot be effective. Build ();
          else {//no network, set timeout of 4 weeks int maxstale = 60 * 60 * 24 * 28;
 Response.newbuilder ()             . Header ("Cache-control", "Public, only-if-cached, max-stale=" + Maxstale). Removeheader ("Pragma
        "). Build ();
      return response;
    }
    };
    Client = new Okhttpclient.builder (). cache (Cache). Addinterceptor (Interceptor). Build (); Retrofit = new Retrofit.builder (). BaseURL (retrofitapi.basic_daily). Addconverterfactory (gsonconverterfact
    Ory.create ()). Addcalladapterfactory (Rxjavacalladapterfactory.create ()). Client (client). Build ();
 Retrofitapi = Retrofit.create (Retrofitapi.class);

The following code is then invoked to get the serialized object after the request

Retrofitapi.getdaily ().
        Subscribeon (Schedulers.io ()).
        Observeon (Androidschedulers.mainthread ())
        . Subscribe (new observer<dailybean> () {
          @Override public
          void oncompleted () {

          }

          @Override
          public void OnError (Throwable e) {
            log.d (tag,e.getmessage ());
          }

          @Override public
          void OnNext (Dailybean bean) {
            listener.ongetdailysuccess (bean);
          }
        });

Finally attach the Retrofit interface section

@GET ("News/latest")
observable<dailybean> getdaily ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.