Example Architecting Android ... The Clean?----Code Analysis

Source: Internet
Author: User

Presention layer: When the entire application starts, it executes dependent initialization. After the project is compiled, the Dagger dependency framework uses ApplicationComponent to generate a daggerapplicationcomponent.1. Start with dependent buildsIn application, calling Initializeinjector () causes the dagger framework to make dependent builds.applicationcomponentProvide context,threadexecutor,postexecutionthread,userrepository dependency on other component
/**
* A component whose lifetime is the life of the application.
*/
@Singleton//Constraints This component to one-per-application or unscoped bindings.
@Component (modules = Applicationmodule.class)
Public interface ApplicationComponent {
void inject (baseactivity baseactivity);

Exposed to sub-graphs.
Context context ();
Threadexecutor Threadexecutor ();
Postexecutionthread Postexecutionthread ();
Userrepository userrepository ();
}

Applicationmodule
/**
* Dagger module that provides objects which would live during the application lifecycle.
*/
@Module
public class Applicationmodule {
Private final androidapplication application;

Public Applicationmodule (androidapplication application) {
this.application = Application;
}

@Provides @Singleton Context Provideapplicationcontext () {
return this.application;
}

@Provides @Singleton Navigator providenavigator () {
return new Navigator ();
}

@Provides @Singleton threadexecutor Providethreadexecutor (jobexecutorJobexecutor) {
return jobexecutor;
}

@Provides @Singleton postexecutionthread Providepostexecutionthread (uithreadUithread) {
return uithread;
}

@Provides @Singleton Usercache Provideusercache (UsercacheimplUsercache) {
return usercache;
}

@Provides @Singleton userrepository provideuserrepository (userdatarepositoryuserdatarepository) {
return userdatarepository;
}
}
In this class, a method for generating dependencies is provided. The provide method that requires a parameter is also generated by the Dagger dependency framework. Parameter Jobexecutor (data module), Uithread (presentation module), Usercacheimpl (Data module), Userdatarepository (data Module) generation method, The dagger relies on the framework to invoke the constructor method of the corresponding class, rather than through provide implementation. For example Jobexecutor (data module):p Ublic class Jobexecutor implements Threadexecutor {@Inject public jobexecutor () {This.workqu    Eue = new linkedblockingqueue<> ();    This.threadfactory = new Jobthreadfactory (); This.threadpoolexecutor = new Threadpoolexecutor (initial_pool_size, Max_pool_size, Keep_alive_time, KEEP_ALIVE_TIME  _unit, This.workqueue, this.threadfactory); }...} Data module: Parameter jobexecutor (data module), Usercacheimpl (Data module), Userdatarepository (data module)Application:
/**
* Android Main Application
*/
public class Androidapplication extends application {

Private ApplicationComponent applicationcomponent;

@Override public void OnCreate () {
Super.oncreate ();
This.initializeinjector ();
}

private void Initializeinjector () {
This.applicationcomponent = Daggerapplicationcomponent.builder ()
. Applicationmodule (New Applicationmodule (This))
. build ();
}

Public ApplicationComponent getapplicationcomponent () {

return this.applicationcomponent;
}
}

2.MainActivity implementationsThe View object is injected with butterknife, eliminating the need to write Findviewbyid.2.1 Implementation of inheritance Baseactivity,baseactivityA. Declares a member with a inject annotation navigator in the OnCreate method, injects the navigator dependency into the current instance. B. Provides three protected methods, one for adding fragment to the current interface, and two for dependency injection.2.2 mainactivity Execution ProcessWhen the user clicks on the R.id.btn_loaddata Button, it jumps to the interfaceuserlistactivity.3.UserListActivity implementationsA. Interface loading, using Userlistfragment.  B. In the OnCreate method, perform the dependency initialization that usercomponent contains. private void Initializeinjector () {this.usercomponent = Daggerusercomponent.builder (). ApplicationComponent (Get  ApplicationComponent ()). Activitymodule (Getactivitymodule ()). build (); The dependency generated by usercomponent is injected into the userlistfragment,userdetailsfragment. Userlistfragment,userdetailsfragment invokes the inject method of the Usercomponent instance.usercomponent as follows:the dependency that can be injected into the userlistfragment,userdetailsfragment isGetuserlistusecase,getuserdetailsusecase.
,
/** 
* A scope {@link com.fernandocejas.android10.sample.presentation.internal.di.PerActivity} component.
* Injects user specific fragments.
*/
@PerActivity
@Component (dependencies = Applicationcomponent.class,)
public interface Usercomponent extends activitycomponent {
void inject (userlistfragment userlistfragment);
void inject (userdetailsfragment userdetailsfragment);
}

/** 
* A base component upon which fragment ' s and depend.
* Activity-level components should extend This component.
*
* subtypes of activitycomponent should is decorated with annotation:
* {@link com.fernandocejas.android10.s ample.presentation.internal.di.PerActivity}
*/
@PerActivity
@Component (dependencies = Applicationcomponent.class, modules = activitymodule.class)
Public interface Activitycomponent {
//exposed to Sub-graphs.
activity activity ();
}
/**
* A module to wrap the Activity state and expose it to the graph.
*/
@Module
public class Activitymodule {
Private final activity activity;

Public Activitymodule (activity activity) {
This.activity = activity;
}

/**
* Expose the activity to dependents in the graph.
*/
@Provides @PerActivity Activity activity () {
return this.activity;
}
}
/**
* Dagger module that provides user related collaborators.
*/
@Module
public class Usermodule {

private int userId =-1;

Public Usermodule () {}

Public usermodule (int userId) {
This.userid = userId;
}

@Provides @PerActivity @Named ("userlist") usecase providegetuserlistusecase (
getuserlistusecase getuserlistusecase) {
return getuserlistusecase;
}

@Provides @PerActivity @Named ("Userdetails") usecase providegetuserdetailsusecase (
userrepository userrepository, Threadexecutor threadexecutor,
Postexecutionthread Postexecutionthread) {
return new Getuserdetailsusecase (UserId, Userrepository, Threadexecutor, postexecutionthread);
}
}
implementation of the 4.UserListFragmentThe a.userlistfragment implements the Userlistview interface, which is used to represent the view layer. B.userlistfragment communicates with the host activity through the Userlistfragment declaration of the interface Userlistlistener.
@Override public void Onattach (activity activity) {
Super.onattach (activity);
if (activity instanceof Userlistlistener) {
This.userlistlistener = (userlistlistener) activity;
}
}
C. When the host activity is successfully created, the callback method:
@Override public void onactivitycreated (Bundle savedinstancestate) {
Super.onactivitycreated (savedinstancestate);
This.initialize ();
This.loaduserlist ();
}
In the Userlistfragment class, a member @inject Userlistpresenter Userlistpresenter is declared with the Inject annotation, and then the Usercomponent instance method is called Inject, You can inject dependent userlistpresenter into the userlistfragment instance. Call Userlistpresenter's method Setview to establish a relationship between presenter and view.
private void Initialize () {
This.getcomponent (Usercomponent.class). inject (this);
This.userListPresenter.setView (this);
}
Calling the Loaduserlist method loads all user data.
/**
* Loads all users.
*/
private void Loaduserlist () {
This.userListPresenter.initialize ();
}
The data loading operation of the interface is encapsulated in the Userlistpresenter initalize method. Display interface loading effect; perform get data operation; After the data is loaded successfully, the corresponding interface is displayed. These are implemented and controlled by Userlistpresenter.5.UserListPresenterA. Call the constructor method, construct the parameters of the method, and inject it by dagger.
@Inject
Public Userlistpresenter (@Named ("userlist") usecase getuserlistusercase, Usermodeldatamapper usermodeldatamapper) {
This.getuserlistusecase = Getuserlistusercase;
This.usermodeldatamapper = Usermodeldatamapper;
}
B. Provide the Initialize method for other classes to invoke. Call this method, display the interface loading effect, get all user data.
/**
* Initializes the presenter by start retrieving the user list.
*/
public void Initialize () {
This.loaduserlist ();
}

/**
* Loads all users.
*/
private void Loaduserlist () {
This.hideviewretry ();
This.showviewloading ();
This.getuserlist ();
}
private void Getuserlist () {
This.getUserListUseCase.execute (this); The classes on the domain layer are used here, and the domain layer provides the use case classes. A use case class represents a representation of a business, where it represents the Get user list.

}

6.UserListPresenter and UseCase collaboration  userlistpresenter and UseCase collaborate, using the  the RxJava Android Module framework   1. Userlistpresenter belongs to the presention layer, which relies on the domain layer and the data layer.  2.usecase is the domain layer, and its instance is getuserlistusecase, which is specified by the dependency definition package in the presention layer, The following:com.fernandocejas.android10.sample.presentation.internal.di.modules.usermodule:   @Provides @ Peractivity @Named ("userlist") usecase providegetuserlistusecase (      Getuserlistusecase Getuserlistusecase) {    return getuserlistusecase; } -----So, getuserlistusecase is to be injected, To add a @inject annotation to its constructor.  3.userlistpresenter and Getuserlistusecase,userlistpresenter are a subscriber This subscriber subscribes to a stream that is a method of the Clouduserdatastore instance getuseentitylist () output comes after the mapped stream, which is the:   of this look @Override public Observable<list<user>> getusers () {   //we always get all users from the cloud    final U Serdatastore Userdatastore = This.userDataStoreFactory.createCloudDataStore ();    return Userdatastore.getuserentitylist (). Map (userlistentityMapper); }   summarizes the classes involved and the layer in which they are located:  Presentation layer:Userlistpresenter.Domain layer:Getuseerlistusecase,usecaseData layer:The Userdatarepository,clouduserdatastore,userdatastorefactory presentation layer relies on the domain layer and the data layer.7. Framework technology used throughout the project1.Dagger relies on builds, which define dependent build rules. Application of the 2.RxAndroid responsive programming paradigm to handle asynchronous events in the same way as event streams. 3.okHttp, the network request is applied to the framework.8. The whole project read down and can learn something1. Using dependency injection, one instance contains other instances, and in obtaining the use of other instances, dependency injection is used to not expose the way other instances are generated. In this way, the user is only concerned with the use, no need to focus on how to instantiate, other instances of the process of instantiation of the user is hidden. 2. Layered, sub-modules, this to the meaning of the function of the division, according to the point of concern to divide. Presentation layer, we only focus on the interface display, we in this layer, we only need to focus on the interface display aspects of the code, we just put the interface to show the code on this layer, but also dependent on the generated code. In this layer, we focus only on the interface code, as well as on the generated rules. Domain layer, domain layer, use case layer, the name of the package from this module can be known, it represents a high degree of abstraction of the business, the system platform-independent business. In this application, there are two business, one is to get the user list, and the other is to get the user's details. In this layer, the implementation code for the business is stored. The data layer, and the implementation code of the datastore is placed on this layer.rules for dependencies between tiers:Presention layer------>domain layer-------Get data---->data Layer

Reference: http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/

Example Architecting Android ... The Clean?----Code Analysis

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.