Cache Network data using RX

Source: Internet
Author: User
Tags throwable

Welcome to follow my GitHub and follow my csdn.

Rxjava is responsive programming, which is widely used when processing network data asynchronously.
We can also use some Rx features to gracefully cache network data.

Cache mode: Read the database, display, request data, store to the database, and then update the page.

Using the standard combination of DAGGER2+RETROFIT+RX, let me explain how to use it.

GitHub

1. Framework

Regular items, including jump caches and non-cached pages, load data for 3 seconds of delay in order to simulate a slow environment.

 Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); }//Jump no cache     Public void Gotonocache(View view) {StartActivity (NewIntent ( This, Nocacheactivity.class)); }//jump with cache     Public void Gotocache(View view) {StartActivity (NewIntent ( This, Cacheactivity.class)); }}
2. No cache

Dependency Injection three key parts, Application/component/module.

public   class  rcapplication  extends  application     { private  apicomponent mapicomponent;  @Override  public  void  oncreate         () {super . OnCreate (); Mapicomponent = Daggerapicomponent.builder (). Apimodule (new  apiModule (
    
     this )). Build (); } 
     public  apicomponent 
     getapicomponent  () {
     
      return  mapicomponent; }}
     
    
@Singleton@Component(modules = ApiModule.class)publicinterface ApiComponent {    void inject(NocacheActivity activity);    void inject(CacheActivity activity);}
@Module Public  class apimodule {    PrivateApplication mapplication; Public Apimodule(Application application)    {mapplication = Application; }@Provides    @Singleton     PublicApplicationprovideapplication() {returnMapplication; }@Provides    @SingletonGithubclient providegithubclient () {return NewGithubclient (); }@ProvidesObservablerepodb Provideobservablerepodb () {return NewObservablerepodb (mapplication); }}

The module provides application information, GitHub's network request, database.
@Singleton represents a singleton pattern, and all injections have an instance.

page, display the list information using Recyclerview, and display the ProgressBar at load time.

/** * No cache activity * <p> * Created by Wangchenlong on 16/1/18. * * Public  class nocacheactivity extends Activity {    @Bind(r.id.nocache_rv_list) Recyclerview mrvlist;@Bind(r.id.nocache_pb_progress) ProgressBar mpbprogress;@InjectApplication mapplication;@InjectGithubclient mgithubclient;PrivateListAdapter Mlistadapter;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_nocache); Butterknife.bind ( This); ((rcapplication) getapplication ()). Getapicomponent (). Inject ( This); Linearlayoutmanager LayoutManager =NewLinearlayoutmanager (mapplication);        Mrvlist.setlayoutmanager (LayoutManager); Mlistadapter =NewListAdapter ();    Mrvlist.setadapter (Mlistadapter); }@Override protected void Onresume() {Super. Onresume ();//Delay 3 seconds, simulation effectMgithubclient.getrepos ("Spikeking"). Delay (3, timeunit.seconds). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()) . Subscribe ( This:: Onsuccess, This:: OnError);    Mpbprogress.setvisibility (view.visible); }Private void onsuccess(arraylist<repo> repos)        {Mlistadapter.setrepos (repos);    Mpbprogress.setvisibility (view.invisible); }Private void OnError(Throwable throwable)    {mpbprogress.setvisibility (view.invisible); }}

By observing, it can be found that prolonged display of white screen will degrade the user experience. Let me take a look at the cache mode.

3. Caching

Cache mode: Read the database, display, request data, store to the database, and then update the page.
It is recommended to use a script to generate a database processing class, using the method reference, to automatically generate DBHelper scripts .

Home page logic.

 Public  class cacheactivity extends Activity {    @Bind(r.id.cache_rv_list) Recyclerview mrvlist;//List    @Bind(R.id.cache_srl_swipe) Swiperefreshlayout Msrlswipe;//Refresh    @InjectApplication mapplication;@InjectObservablerepodb Mrepodb;@InjectGithubclient mgithubclient;PrivateListAdapter Mlistadapter;//Recyclerview Adapter    @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_cache); Butterknife.bind ( This);//Injection class((rcapplication) getapplication ()). Getapicomponent (). Inject ( This); Linearlayoutmanager LayoutManager =NewLinearlayoutmanager (mapplication);        Mrvlist.setlayoutmanager (LayoutManager); Mlistadapter =NewListAdapter ();        Mrvlist.setadapter (Mlistadapter); Msrlswipe.setonrefreshlistener ( This:: Fetchupdates); }@Override protected void Onresume() {Super. Onresume (); Mrepodb.getobservable (). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthrea D ()). Subscribe ( This:: SetData);        Fetchupdates (); Toast.maketext (Mapplication,"Updating", Toast.length_short). Show (); }//Set data, update completion will call    Private void SetData(arraylist<repo> repos)        {Mlistadapter.setrepos (repos); Toast.maketext (Mapplication,"Update Complete", Toast.length_short). Show (); }Private void fetchupdates() {//Delay 3 seconds, simulation effectMgithubclient.getrepos ("Spikeking"). Delay (3, timeunit.seconds). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()) . Subscribe (Mrepodb::insertrepolist, This:: Fetcherror, This:: FetchComplete); }Private void Fetcherror(Throwable throwable) {msrlswipe.setrefreshing (false); }Private void FetchComplete() {msrlswipe.setrefreshing (false); }}

Observer for the database

/** * Redo Viewer * <p> * Created by Wangchenlong on 16/1/18. */ Public  class observablerepodb {    PrivatePublishsubject<arraylist<repo>> Mpublishsubject;//Post a theme    PrivateRepodbhelper Mdbhelper;//Database     Public Observablerepodb(Context context) {Mdbhelper =NewRepodbhelper (context);    Mpublishsubject = Publishsubject.create (); }//Return to viewer     PublicObservable<arraylist<repo>>getobservable() {observable<arraylist<repo>> firstobservable = observable.fromcallable ( This:: Getrepolist);returnFirstobservable.concatwith (Mpublishsubject);//Connection Publishing topic}//Get data from the database    PrivateArraylist<repo>getrepolist() {mdbhelper.openforread (); arraylist<repo> repos =NewArraylist<> (); Cursor C = Mdbhelper.getallrepo ();if(!c.movetofirst ()) {returnRepos//return null} do {//Add DataRepos.add (NewRepo (C.getstring (repodbhelper.repo_id_column_position), c.getstring (repodbhelper.re po_name_column_position), c.getstring (repodbhelper.repo_description_column_position),NewRepo.owner (C.getstring (repodbhelper.repo_owner_column_position),"","",""))); } while(C.movetonext ());        C.close (); Mdbhelper.close ();returnRepos }//Insert Repo list     Public void insertrepolist(arraylist<repo> repos)        {Mdbhelper.open (); Mdbhelper.removeallrepo (); for(Repo Repo:repos) {Mdbhelper.addrepo (Repo.getid (), Repo.getname (), Rep        O.getdescription (), Repo.getowner (). GetLogin ());        } mdbhelper.close (); Mpublishsubject.onnext (repos);//Will call Update data}}

This section is the key to implementing a network request to synchronously insert the database and update the page.
Association Publishsubject, after the insert data is complete, invokes the binding observer and updates the page.
That is . Concatwith (Mpublishsubject) and mpublishsubject.onnext (repos).

Rx is really elegant in dealing with network requests and deserves the perfect person to use.

OK, that ' s all! Enjoy it.

Cache Network data using RX

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.