Android uses Rxjava+retrofit +realm combination to load Data <读取缓存 显示="" 请求网络数据="" 缓存最新数据="" 更新界面=""> (ii) __android

Source: Internet
Author: User

Continue to refine the last muddled process.

The principle is still the same. Don't understand. Take a look.
Android uses rxjava+retrofit +realm combination load Data < read cache display request network data cache latest Data Update interface > (i)

This integration is the database realm Click to view the Chinese document interested can go to see.
The reason for using realm is that it is the same as retrofit. Born to support Rxjava, of course, there are other, but I did not use.


Realm configuration Applaction If multiple processes are configured. It is better to judge the package name to prevent multiple calls

private void Initrealm () {
        realmconfiguration realmconfiguration = new Realmconfiguration.builder (this)
                . Name ("Xxx.realm")
                . Schemaversion (1)
                . Rxfactory (New Realmobservablefactory ())//default Rxjava support, seemingly not write can also
                . Deleterealmifmigrationneeded ()//test use, delete the original data
//                . EncryptionKey (key)
//                . Modules (New Myschemamodule ())
//                    . Migration (migration)
                . Build ();
        Realm.setdefaultconfiguration (realmconfiguration);
    }

Realm with Rxjava Query method, Official document configuration

Combining Realm, Retrofit and Rxjava (Using RETROLAMBDA syntax for brevity)
//Load All persons and merge them with Their latest stats from GitHub (if they have any) Realm Realm
= Realm.getdefaultinstance ();
Githubservice API = Retrofit.create (githubservice.class);
Realm.where (Person.class). Isnotnull ("username"). Findallasync (). Asobservable ().
    Filter (persons.isloaded)
    . Flatmap (Persons-> Observable.from (persons))
    . Flatmap (Person-> api.user (Person.getgithubusername ( )
    . Observeon (Androidschedulers.mainthread ()).
    Subscribe (user-> Showuser (user));

Note that the asynchronous query does not block the current thread, as the above code returns an Realmresults instance immediately. If you want to make sure that the realmresults has been loaded, use the filter operator and realmresults.isloaded () method. You can tell if the query is complete by determining whether Realmresults has already been loaded.

The above is the official website document of the words, but according to my actual use. The use of Realm.getdefaultinstance () asobservable () will never be dropped using the OnComplete () method, which is a pit, quite deep, and, in the course of use, Call OnNext () multiple times, causing multiple calls in Subscriber.onnext (), which means the interface will be refreshed multiple times
If you want to take a data, you need to use Filter/first ()

Query code

 final Realm Realm = Realm.getdefaultinstance (); observable<recommendhome> Datasourcefromdb = Realm.where (Recommendhome.class). FindFirstAsync () .< Recommendhome>asobservable (). Filter (New Func1<recommendhome, boolean> () {@O Verride Public Boolean Call (Recommendhome recommendhome) {LOGUTILS.W (TAG, "Da
                        Tasource from Realm ");
                    return recommendhome.isloaded (); 
                    (). dooncompleted (New Action0 () {@Override
                            public void Call () {if (realm = null &&!realm.isclosed ()) {
                        Realm.close (); }
                    }
                });

Need to explain the realm wire protection mechanism, can not multithreading access to the same instance, it can only be used in the creation of his thread, according to the official website document that the asynchronous query will not block the current thread, I believe that, that is, the Rxjava in the very convenient switching thread here is the egg

Combining the query with the network request, the concat that I have used here is the general meaning of sending multiple observable data to a subscriber. Based on this principle. Modifying the Netmanager class is the same one only modifies the method

 public void Getrecommenddatasource (subscriber<recommendhome> subscriber, Boolean isconnection) {final real
        M realm = Realm.getdefaultinstance (); observable<recommendhome> Datasourcefromdb = Realm.where (Recommendhome.class). FindFirstAsync () .< Recommendhome>asobservable (). Filter (New Func1<recommendhome, boolean> () {@O Verride Public Boolean Call (Recommendhome recommendhome) {LOGUTILS.W (TAG, "Da
                        Tasource from Realm ");
                    return recommendhome.isloaded (); 
                    (). dooncompleted (New Action0 () {@Override
                            public void Call () {if (realm = null &&!realm.isclosed ()) {
                        Realm.close ();
        }
                    }
                }); Observable<recommendhome> datasourcefromnet = Retrofitmanager.getwebapiservice (). Getrecommendhomedatas () . Doonnext (New action1<recommendhome> () {@Override public void
                        Call (Recommendhome recommendhome) {LOGUTILS.W (TAG, ' Save to DB ');
                        Realm Realm = Realm.getdefaultinstance ();
                        Realm.begintransaction ();
                        Realm.copytorealmorupdate (Recommendhome);
                        Realm.committransaction ();
                    Realm.close ();
                }). Subscribeon (Schedulers.io ()). Unsubscribeon (Schedulers.io ())
        . Observeon (Androidschedulers.mainthread ());
        if (isconnection) {observable.concat (Datasourcefromdb, datasourcefromnet). Subscribe (subscriber);
        else {datasourcefromdb.subscribe (subscriber);
 }   } 

Call directly in the activity/fragment to pass in the Subscriber<t>, where the Boolean parameter is to determine the network connection state, optional

Log is as follows

No network status

07-22 16:11:29.496 16479-16479:datasource from Realm 07-22 16:11:29.746 and 16479-16479:datasource from
realm
07-22 16:11:29.746 16479-16479:subscriber onnext 07-22 16:11:29.766 16479-16479:subscriber onCompleted

Have network status

07-22 16:13:13.246 16479-16479:datasource from Realm 07-22 16:13:13.246 and 16479-16479:datasource from
realm
07-22 16:13:13.246 16479-16479:subscriber onnext
07-22 16:13:13.746 to DB
07-22 16479-19234:save 1 6479-16479:subscriber onnext
07-22 16:13:13.836 16479-16479:subscriber oncompleted

To this basically finish reading data-> display-> request network data-> cache new Data-> update interface
That's it

-end

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.