Initial involvement of Rxandroid combined with glide for multi-image loading operations

Source: Internet
Author: User

Reprint please indicate the source: Wang 亟亟 's way of Daniel

Originally the weekend would like to send and then all kinds of procrastination will not then, then write this morning, no more nonsense to start the subject

What is Rxjava or rxandroid I don't have much nonsense, theoretical knowledge a lot of people give us a good. Just to be able to see it alone can understand, I here directly to the Portal: Https://github.com/lzyzsd/Awesome-RxJava (very rich, the basic concept after reading)

So the question is, what am I going to do when everyone else explains it? Let's do a simple example. Just last week, I told you a glide.

Let's open the app and then there's a recycleview inside there's a bunch of pictures and then there's text, the text is local, the picture is online. The logic flow is very easy, to say how to realize and then lead the protagonist.

Package Structure:

glidemoduleconfig Configuration Glide
statusbarcompat Immersive menu strip implementation (Xiang Brother that buckle, this is actually dispensable main default color is too ugly)
Testobj The property model of the Page object (you can also not, personal habits)
Then there is the business implementation of the Mainactivity and adapter DataAdapter.

We look at one class first Glidemoduleconfig

/** * Created by Jiajiewang on 16/3/25. * * Public  class glidemoduleconfig implements glidemodule {    //Create settings here, the image quality mentioned in the previous article can be set here    //can also set cache pool parameters for what    @Override     Public void applyoptions(context context, Glidebuilder Builder) {//Set the default picture formatBuilder.setdecodeformat (decodeformat.prefer_argb_8888);//Set the location of the cacheBuilder.setdiskcache (NewExternalcachediskcachefactory (Context,"My_cache_location", -*1024x768*1024x768)); }//Register here Modelloaders    @Override     Public void registercomponents(context context, Glide Glide) {    }}

Here do some configuration work, in detail what can be seen staring

Testobj used to refer a picture address and text content to Recycleview

publicclass TestOBJ {    public String imageUrl;    public String content;}

Xiang elder brother that class does not explain, can own to search searches Baidu first article is. Let's look at the adapter again.

DataAdapter (The explanation of the important steps is also in the gaze)

 Public  class DataAdapter extends recyclerview. Adapter {Context context; List<testobj> Testobjs; Public DataAdapter(Context context) { This. Context = Context; }//Get layout    @Override     PublicRecyclerview.viewholderOncreateviewholder(ViewGroup parent,intViewType) {View view = Layoutinflater.from (Parent.getcontext ()). Inflate (r.layout.item_layout, parent,false);return NewDataviewholder (view); }//Detailed item loading picture fill data    @Override     Public void Onbindviewholder(Recyclerview.viewholder holder,intPosition) {Dataviewholder Dataviewholder = (dataviewholder) holder; Testobj obj = testobjs.get (position);//Get the context object first, then load the detailed URL and populate it with the control.Glide.with (Holder.itemView.getContext ()). Load (Obj.imageurl). into (DATAVIEWHOLDER.IMAGEIV);    DataViewHolder.contentTV.setText (obj.content); }@Override     Public int GetItemCount() {returnTESTOBJS = =NULL?

0 : testOBJs.size(); } //控件对象Holder static class DataViewHolder extends RecyclerView.ViewHolder { ImageView imageIV; TextView contentTV; public DataViewHolder(View itemView) { super(itemView); imageIV = (ImageView) itemView.findViewById(R.id.imageIV); contentTV = (TextView) itemView.findViewById(R.id.contentTV); } } //刷新数据用 public void updateData(List<TestOBJ> testOBJs) { this.testOBJs = testOBJs; notifyDataSetChanged(); }}

The data layer is OK, let's take a look at the business layer

 Public  class mainactivity extends appcompatactivity {Toolbar Toolbar;    Recyclerview Recycleview; DataAdapter DataAdapter;//url Data SourceString data[] = {"Http://hiphotos.baidu.com/zhixin/abpic/item/4651a712c8fcc3cea97dbce49045d688d53f206c.jpg","Http://pic.5442.com/2014/0930/06/5442.jpg","Http://img5q.duitang.com/uploads/item/201410/22/20141022214043_5EEKH.thumb.224_0.jpeg","Http://img5.duitang.com/uploads/item/201512/08/20151208163159_HGEM2.thumb.224_0.png","Http://img4.duitang.com/uploads/item/201510/29/20151029224537_ijEKF.thumb.224_0.jpeg","Http://img5.imgtn.bdimg.com/it/u=1230273521,1023320328&fm=21&gp=0.jpg"};//The person being observedObservable Observable = Observable.create (NewObservable.onsubscribe<list<testobj>> () {@Override         Public void Pager(SUBSCRIBER&LT;?Superlist<testobj>> subscriber) {Subscriber.onnext (Makedata ());        Subscriber.oncompleted (); }    });//ObserverObserver<list<testobj>> Observer =NewObserver<list<testobj>> () {@Override         Public void oncompleted() {LOGUTILS.D ("--->oncompleted"); }@Override         Public void OnError(Throwable e) {Toast.maketext (mainactivity). This,"Load Failed", Toast.length_short). Show (); }@Override         Public void OnNext(list<testobj> Testobjs)            {testobjs.size (); LOGUTILS.D ("--->onnext testobjs.size ()"+ testobjs.size ());//Refresh DataDataadapter.updatedata (TESTOBJS); }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Init ();        Logic ();        Setsupportactionbar (ToolBar); Statusbarcompat.compat ( This, Getresources (). GetColor (R.color.status_bar_color)); Statusbarcompat.compat ( This); }Private void Init() {LOGUTILS.D ("--->init");        ToolBar = (ToolBar) Findviewbyid (R.id.toolbar);        Recycleview = (Recyclerview) Findviewbyid (R.id.recycleview); Observable.subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscrib    E (Observer); }Private void Logic() {LOGUTILS.D ("--->logic"); DataAdapter =NewDataAdapter (mainactivity. This); Recycleview.setlayoutmanager (NewLinearlayoutmanager (mainactivity. This));        Recycleview.setadapter (DataAdapter); LOGUTILS.D ("--->glide.getphotocachedir"+ Glide.getphotocachedir (mainactivity. This,"My_cache_location")); }//Manufacturing Data    PrivateList<testobj>Makedata() {list<testobj> List =NewArraylist<> (); Testobj Testobj; for(intK =0; K <5; k++) {testobj =NewTestobj (); Testobj.content ="The title, you don't obey."+ K +"a";            Testobj.imageurl = Data[k];        List.add (Testobj); } LOGUTILS.D ("The length of the--->list equals"+ list.size ());returnList }@Override    protected void OnPause() {Super. OnPause ();//Clear RequestGlide.clear (Recycleview); }@Override    protected void OnDestroy() {Super. OnDestroy (); LOGUTILS.D ("--->ondestroy");//Must be used by the main threadGlide.get ( This). Clearmemory ();//glide.get (this). Cleardiskcache (); Non-main thread}}

Explain:
We have defined an observer and a observed person, and then since

 observable.subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(observer);

After the initiation of the registration, the observer's relevant callback will be triggered just by biting the observer, and we'll take a look at the print order of the log.

Or in a bunch of activity lifecycles, run in the process of our data touching you. The folder that we glide cache, which is consistent with our presets, then runs OnNext and then oncompleted. There was no accident, and I didn't paint the onerror.

/data/user/0/sample.wjj.rxandroidglidedemo/cache/MY_CACHE_LOCATION

Source code Address: Https://github.com/ddwhan0123/RxAndroidDemo

Initial involvement of Rxandroid combined with glide for multi-image loading operations

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.