Introduction to MVP Mode (combined with Rxjava,retrofit)

Source: Internet
Author: User
Tags set time

This article Mvp's sample implementation results:

  

GitHub Address: Https://github.com/xurui1995/MvpSample

  

The usual, before talking about the MVP model understanding of the MVC pattern, to understand the shortcomings of MVC. We didn't know why we had to use MVP.

As for the MVC diagram, I found some pictures on the Internet. As follows:

MVC pattern in the development of the Web or management system of many applications, our view with people, people click on the mouse or enter something, The view will send the corresponding instructions to Controller,controller

received instructions, and then to call the model of the method to update the data (most of the data additions and deletions), model processing finished, view Refresh display .

  Disadvantages of the MVC pattern:

1: in android, If we want to use the MVC pattern, then what does each layer represent?

You may say: the view corresponds to the Android Layout.xml,model for the operation of the database in the android, the operation of the network is placed here, the controller corresponds to the activity!

You are right, but you do not think this correspondence is not good, if layout.xml corresponds to view, then if we want to dynamically control the addition of some view control or change the background, then what to do?

Answer: Add code to Activity. This is one of the shortcomings:activity is both Father (view) and mother (controller), Layout.xml represents the view layer control is too weak.

2: look again at the structure of our mvc, theview and model are interrelated, there is a coupling relationship, which makes the test maintenance Difficult. When we want to change a part of the project, the lack of discovery is too difficult to remove! The method of this part class is scattered in many Places. About the structure of mvc, forget where to hear a classic words, write three letters, m,v,c, casually with a line or arrows, and finally the structure of MVC.

After the mvc, the protagonist is on the chart of our Mvp.

  

The benefits are self-evident, and the view and model cannot Communicate.

View layer is only responsible for the view, the operation of the view layer when the event sent to Presenter,presenter to operate model, the model, and then to notify the view corresponding Update.

More about the MVP Concept:

"translate" the MVP design mode of Android

Illustrations of MVC,MVP and MVVM

next, take a look at how we use the MVP model in our project, and by the way retrofit and Rxjava are used, it is recommended that you understand their usage first.

First look at our needs: enter the github login name, Click the search button, search and display the results (login name, nickname, Followers,following).

  

The final project Structure:

Bean class:

public class User {    private String login;    Private String name;    private int followers;    private int following;    public int getfollowers () {        return followers;    }    public void Setfollowers (int followers) {        this.followers = followers;    }    public int getfollowing () {        return following;    }    public void setfollowing (int Following) {        this.following = following;    }    Public String getlogin () {        return login;    }    public void Setlogin (String login) {        this.login = login;    }    Public String getName () {        return name;    }    public void SetName (String name) {        this.name = name;    }}

The retrofit class primarily encapsulates network requests that utilize retrofit

public interface Githubservice {    @GET ("/users/{user}")    observable<user> getUser (@Path ("user") String username);}

 

public class Httpmethods {public static final String Base_url = "https://api.github.com";    private static final int default_timeout = 5;    Private Retrofit Retrofit;    Private Githubservice mgithubservice;  Construction method Private Private Httpmethods () {//manually Create a okhttpclient and set time-out okhttpclient.builder Httpclientbuilder = new        Okhttpclient.builder ();        Httpclientbuilder.connecttimeout (default_timeout, timeunit.seconds); Retrofit = new Retrofit.builder (). client (httpclientbuilder.build ()). addconverterfactory (Gs Onconverterfactory.create ()). addcalladapterfactory (rxjavacalladapterfactory.create ()). Base        URL (base_url). Build ();    Mgithubservice = Retrofit.create (githubservice.class);    } private static class Singletonholder{private static final Httpmethods INSTANCE = new Httpmethods (); }//get a singleton public static httpmethods getinstance () {return singletonholder.instance;                } public void GetUser (subscriber<user> subscriber, String loginName) {mgithubservice.getuser (loginName) . Subscribeon (schedulers.io ()). unsubscribeon (schedulers.io ()). observeon (androi    Dschedulers.mainthread ()). Subscribe (subscriber); }}

    

Now we're going to think about our MVP model, some of which start with our view layer, and we need to first list the view-related methods (no logic involved).

1. An attempt to display XML

2.ProgressDialog Display

3.ProgressDialog disappears

4. Display Error messages

Next look at the specific code:

Activity_main.xml

<?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 "> <textview android:id=" @+id/tv "android:layout_width=" match_parent "andro        id:layout_height= "80dp"/> <edittext android:id= "@+id/ed_text" android:layout_centerinparent= "true"     android:hint= "please Enter the search login name" android:layout_width= "wrap_content" android:layout_height= "wrap_content"/>        <button android:id= "@+id/search_btn" android:text= "query" android:layout_centerhorizontal= "true" android:layout_below= "@+id/ed_text"android:layout_width=" wrap_content "android:layout_height=" wrap_content "/></relativelayout> 

baseview,basepresentor, Basemodel three X interface

  

public interface Baseview {    void Showprogressdialog ();    void Hideprogressdialog ();    void Showtext (User userbean);    void Showerrormessage (String text);}

Public interface basepresenter<t extends baseview> {    void Attachview (T view);    void Detachview ();    void Searchuser (String loginName);}

public interface Basemodel {    void GetUser (subscriber<user> subscribe,string loginName);}

The second interface interface basepresenter<t extends Baseview> is the key, as for why, you can use the implementation class to Explain.

The mainactivity implements the Baseview interface as the view Layer.

  

public class Mainactivity extends appcompatactivity implements Baseview {@InjectView (r.id.tv) TextView mtextview;    @InjectView (r.id.search_btn) Button mbutton;    @InjectView (r.id.ed_text) EditText medittext;    Private ProgressDialog dialog;    Private Mainpresenter mmainpresenter;        @Override protected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Butterknife.inject (this);        Initview ();        Mmainpresenter=new Mainpresenter ();    Mmainpresenter.attachview (this);        }/** * Some initialization, here is the initialization of progressdialog */private void Initview () {dialog=new progressdialog (this);        Dialog.setprogressstyle (progressdialog.style_spinner);    Dialog.setmessage ("in search"); } @OnClick (r.id.search_btn) void search (view view) {mmainpresenter.searchuser (medittext.gettext (). toString ())    ;     } @Override public void Showprogressdialog () {   Dialog.show ();    } @Override public void Hideprogressdialog () {dialog.dismiss ();         } @Override public void Showtext (User Userbean) {String temp=getresources (). getString (r.string.user_format); String str=string.format (temp,userbean.getlogin (), userbean.getname (), userbean.getfollowers (),        Userbean.getfollowing ());    Mtextview.settext (str);    } @Override public void Showerrormessage (String Text) {toast.maketext (this,text,toast.length_short). show ();        } @Override protected void OnDestroy () {super.ondestroy ();    If (mmainpresenter!=null) Mmainpresenter.detachview (); }}

When clicking on the button to generate the event, the logic is given to Mainpresenter to deal with, the corresponding relationship v--> P

Here's a look at the mainpresenter code and the model Code.

  

public class Mainpresenter implements Basepresenter {private Baseview mmainview;    Private Mainmodel mmodel;    Public mainpresenter () {mmodel=new Mainmodel ();    } @Override public void Attachview (baseview View) {mmainview=view;    } @Override public void Detachview () {mmainview=null; } @Override public void Searchuser (String loginName) {if (textutils.isempty (loginname.trim ())) {mM            Ainview.showerrormessage ("please Enter a valid login name");        Return                } if (mmodel!=null) {mmodel.getuser (new subscriber<user> () {@Override                public void OnStart () {//show dialog box Mmainview.showprogressdialog () first; } @Override public void oncompleted () {//request ends, Dialog Disappears mmainview.hideprogr                Essdialog (); } @Override public void OnError (throwable E) {//error mMainview.showerrormessage ("search failed");                } @Override public void OnNext (user user) {mmainview.showtext (user);        }},loginname); }    }}

public class Mainmodel implements basemodel{    @Override public    void GetUser (subscriber<user> subscriber, String loginName) {        httpmethods.getinstance (). getUser (subscriber,loginname);    }}

The model implementation class here is simpler and uses the encapsulated httpmethods method directly. (model can be understood as a warehouse administrator, our network can also be understood as a large warehouse).

In Mainpresenter we are actually using the model method, that is, p-->m

Then use the Rxjava Observer to observe the results, then call the View method refresh interface, that is, p-->v

  

This time back to see our MVP chart, is not identical? (how to get the mvp, you can try the contract Class)

  

Introduction to MVP Mode (combined with Rxjava,retrofit)

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.