An introduction to Android Learning Flux architecture _android

Source: Internet
Author: User
Tags static class

Introduction to Flux Architecture

The Flux architecture is used by Facebook to build their client Web applications. Like clean architecture, it is not designed for mobile applications, but its features and simplicity allow us to use it well in Android projects.

The most characteristic of flux mode is one-way data flow, its UI state update pattern inherits the design idea of MVC pattern. Flux is not a concrete framework, but a set of patterns to handle UI problems, and the Android flux is not a concrete framework, you don't need to import or integrate any new code, and what you need to do is understand the set of ideas, follow this development pattern, Check out our sample Android code and write our own code.

To understand flux, there are two key features

1, the data flow is always one-way

A one-way data flow is the core of Flux architecture, and it is also easy to learn the reason. As discussed below, it provides a great deal of help when conducting an application test.

2. The application is divided into three main parts:

. View: an Application interface. This creates a response to the user action action .

. Dispatcher: Central hub that delivers all action that is responsible for transporting them up to each Store .

. Store: maintains a specific application domain state. They perform business logic based on the current state response action , and issue an event at the time of completion change . This event is used to view update its interface.

These three parts are Action communicated by: A simple basic object, distinguished by type, that contains the data associated with the operation.

Flux Android Architecture

The purpose of using the Flux Design specification in Android development is to build a framework that is balanced between simplicity and easy scalability testing.

The first step is to find the mapping between the flux element and the Android app component.

Two of these elements are very easy to find and implement.

View: Activity oOrFragment

Dispatcher: An event bus, which will use Otto in my example, but any other implementation should be OK.

Actions

ActionsIt's not complicated. Their implementation is POJO as simple as the two main attributes:

1, type: A string that defines the type of event.

2, Data: a map, loaded this operation.

The store is the hardest part of flux theory.

StoresRespond Dispatcher to the issue Action , execute business logic, and send change events. StoresThe only output is this single event: change . Other components that are Store interested in the internal state must listen to the event and use it to obtain the required data. Finally, stores an interface to obtain the state must be disclosed externally application . This allows view the element to query Stores and then update the UI accordingly.

Here is a simple little demo to tell the whole process. We have one and one on the interface Button and click on it TextView Button to TextView display the text. General implementation, directly in the Activity completion of logic, MVP patterns, in the Presenter layer to carry out, for the flux architecture, how do we achieve it. As we can see from the above figure, it View will be generated Action , then be Dispatcher scheduled, and Store processed to show the data.

How to generate action

The first thing to know Action is what

public class Action {private final String type;

  Private final hashmap<string, object> data;
    Public Action (String type, hashmap<string, object> data) {this.type = type;
  This.data = data;
  public static Builder type (String type) {return new Builder (). with (type);
  Public String GetType () {return type;
  Public HashMap GetData () {return data;
    public static class Builder {private String type;

    Private hashmap<string, object> data; 
      Builder with (String type) {if (type = = null) {throw new IllegalArgumentException ("type May is not null.");
      } this.type = type;
      This.data = new hashmap<> ();
    return this; Public Builder Bundle (String key, Object value) {if (key = = null) {throw new Illegalargumentexcepti
      On ("The Key may is not null.");
      } if (value = = null) {throw new IllegalArgumentException ("value may is not null.");
 }     Data.put (key, value);
    return this; The public Action build () {if (Textutils.isempty (type)) {throw new IllegalArgumentException (' At least O
      NE key is required. ");}
    return new Action (type, data); }
  }
}

Each Action has two attributes, one to mark Type , and another to store the transmitted data by storing it Map .

For Action Type that, we can record all types in a single interface or class. Convenient for us to call.

Public interface Showactions {
  String todo_show = "Todo-show";
  String get_text = "Get-text";
}

How to create Action , define a class that is specifically designed to be defined in terms of the various View events that may arise Action .

public class Actionscreator {

  private static actionscreator instance;

  Final Dispatcher Mdispatcher;

  Actionscreator (Dispatcher Dispatcher) {
    mdispatcher = Dispatcher;
  }

  public static Actionscreator Get (Dispatcher Dispatcher) {
    if (instance = = null) {
      instance = new Actionscreator ( Dispatcher);
    }
    return instance;
  }

  public void Create (String text) {
    mdispatcher.dispatch (showactions.todo_show, Showactions.get_text, text);
  }

When we are ready to use actionscreator to create Action , we do not do it directly with the new action , but we pass it through the scheduler, It was distributed. Here's the event distribution, and we're using Otto 's bus to distribute the event.

public class Dispatcher {private Final bus;

  private static Dispatcher instance;
  Dispatcher (Bus bus) {This.bus = bus;
    public static Dispatcher get (Bus bus) {if (instance = = null) {instance = new Dispatcher (bus);
  return instance;
  public void register (final Object cls) {bus.register (CLS);
  The public void unregister (final Object cls) {bus.unregister (CLS);

  public void Emitchange (Store.storechangeevent o) {post (o);} public void dispatch (String type, Object ... data) {if (Textutils.isempty (type)) {throw new Illegalargumentexcep
    tion ("Type must not to be empty");
    } if (data.length% 2!= 0) {throw new IllegalArgumentException ("Data must be a valid list of key");
    } Action.builder Actionbuilder = Action.type (type);
      for (int i = 0; i < data.length i++) {String key = (String) data[i++];
      Object value = data[i++];
    Actionbuilder.bundle (key, value); Post (ACTIOnbuilder.build ());
  Private Boolean IsEmpty (String type) {return textutils.isempty (type);
  private void Post (final Object event) {Bus.post (event); }
}

In the scheduling process, we will pass in the data to do a resolution, and then based on the data to create a corresponding Action , and then Action distribution, this time to focus on the corresponding Action Store will begin to Action do the appropriate action. In Store , an abstract method onAction is declared to be responsible for Action the judgment and distribution of the, and then the interface is defined as an event change, and StoreChangeEvent when there is a change, through which we can implement this interface, and then add some methods and fields inside to carry the data.

Public abstract class Store {
  final Dispatcher mdispatcher;

  Protected Store (Dispatcher Dispatcher) {
    this.mdispatcher = Dispatcher;
  }

  void Emitstorechange () {
    mdispatcher.emitchange (ChangeEvent ());
  }

  Abstract storechangeevent changeevent ();

  public abstract void OnAction (Action action);

  Public interface Storechangeevent {}

}

Our Custom store class

 public class Showstore extends Store {private static Showstore instance;

  Private String Showtext;
  Public Showstore (Dispatcher Dispatcher) {super (Dispatcher); public static Showstore Get (Dispatcher Dispatcher) {if (instance = = null) {instance = new Showstore (Dispa
    Tcher);
  return instance; 
        @Subscribe public void OnAction (action action) {switch (Action.gettype ()) {case Showactions.todo_show:
        Showtext = ((String) Action.getdata (). Get (Showactions.get_text));
        LOG.I ("Showtext", Showtext);
        Emitstorechange ();
      Break
    Default:break;
  } public String Getshowtext () {return showtext;
  @Override storechangeevent ChangeEvent () {return new showchangeevent (); public class Showchangeevent implements Storechangeevent {}} 

Then we subscribe to the View Activity method of changing time, which enables View a dynamic update of the data in.

 @Subscribe public
  void Showtext (Showstore.showchangeevent event) {
    Mtextview.settext ( Mshowstore.getshowtext ());
   }

Summarize

Through the flux architecture, the process used is that our view events carry data, creating an action of type by a actionscreate, actually completing the process in dispatcher dispatch, The action is then dropped to the store method that subscribes to the action, where all the logic, processing, and even the network request can be initiated to get the data, the processing done, and the result encapsulated into an event, This event then passes the event to the function that subscribed to the event again through the emitchangeevent in the scheduler, and the function that receives the response event is defined in our view to implement the update to our view. The above is the entire content of this article, I hope the content of this article for everyone to learn flux architecture help.

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.