Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A full-featured framework that allows building android applications following the principles of Clean Architecture.

License

NotificationsYou must be signed in to change notification settings

6thsolution/EasyMVP

Repository files navigation

Build StatusDownloadAndroid Arsenal

A powerful, and very simple MVP library withannotation processing andbytecode weaving.

EasyMVP eliminates the boilerplate code for dealing with MVP implementation.

📖Chinese Readme 中文文档

Features

  • Easy integration
  • Less boilerplate
  • Composition over inheritance
  • Implement MVP with just few annotations
  • UseLoaders to preserve presenters across configurations changes
  • SupportClean Architecture approach.

Installation

Configure your project-levelbuild.gradle to include the 'easymvp' plugin:

buildscript {  repositories {...    maven { url"http://dl.bintray.com/6thsolution/easymvp" }   }  dependencies {    classpath'com.sixthsolution.easymvp:easymvp-plugin:1.2.0-beta10'  }}allprojects {  repositories {...      maven { url"http://dl.bintray.com/6thsolution/easymvp" }  }}

Then, apply the 'easymvp' plugin in your module-levelbuild.gradle:

applyplugin:'easymvp'android {...}

There is no need forandroid-apt plugin for android gradle plugin version 2.2.0-alpha1 or higher. But if your are using it, please applyeasymvp plugin afterandroid-apt plugin.

applyplugin:'com.neenbedankt.android-apt'applyplugin:'easymvp'

For reactive API, simply apply the 'easymvp-rx' plugin in your module-levelbuild.gradle and then add the RxJava dependency:

applyplugin:'easymvp-rx'dependencies {  compile'io.reactivex:rxjava:x.y.z'}

Also EasyMVP supports RxJava2:

applyplugin:'easymvp-rx2'dependencies {  compile'io.reactivex.rxjava2:rxjava:x.y.z'}

Note: All snapshot versions are available onjfrog

Usage

First thing you will need to do is to create your view interface.

publicinterfaceMyView {voidshowResult(StringresultText);voidshowError(StringerrorText);}

Then you should implementMyView in yourActivity,Fragment orCustomView.But why?

  • Improve unit testability. You can test your presenter without any android SDK dependencies.
  • Decouple the code from the implementation view.
  • Easy stubbing. For example, you can replace yourActivity with aFragment without any changes in your presenter.
  • High level details (such as the presenter), can't depend on low level concrete details like the implementation view.

Presenter

Presenter acts as the middle man. It retrieves data from the data-layer and shows it in the View.

You can create a presenter class by extending of theAbstractPresenter orRxPresenter (available in reactive API).

publicclassMyPresenterextendsAbstractPresenter<MyView> {}

To understand when the lifecycle methods of the presenter are called take a look at the following table:

PresenterActivityFragmentView
onViewAttachedonStartonResumeonAttachedToWindow
onViewDetachedonStoponPauseonDetachedFromWindow
onDestroyedonDestroyonDestroyonDetachedFromWindow

View Annotations

Well, here is the magic part. There is no need for any extra inheritance in yourActivity,Fragment orView classes to bind the presenter lifecycle.

Presenter's creation, lifecycle-binding, caching and destruction gets handled automatically by these annotations.

For injecting presenter into your activity/fragment/view, you can use@Presenter annotation. Also during configuration changes, previous instance of the presenter will be injected.

EasyMVP usesLoaders to preserve presenters across configurations changes.

Presenter instance will be set to null, afteronDestroyed method injection.

@ActivityView example:

@ActivityView(layout =R.layout.my_activity,presenter =MyPresenter.class)publicclassMyActivityextendsAppCompatActivityimplementsMyView {@PresenterMyPresenterpresenter;@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);    }@OverrideprotectedvoidonStart() {super.onStart();// Now presenter is injected.    }@OverridepublicvoidshowResult(StringresultText) {//do stuff    }@OverridepublicvoidshowError(StringerrorText) {//do stuff    }}
  • You can specify the layout in@ActivityView#layout and EasyMVP will automatically inflate it for you.

@FragmentView example:

@FragmentView(presenter =MyPresenter.class)publicclassMyFragmentextendsFragmentimplementsMyView {@PresenterMyPresenterpresenter;@OverridepublicvoidonResume() {super.onResume();// Now presenter is injected.    }@OverridepublicvoidshowResult(StringresultText) {//do stuff    }@OverridepublicvoidshowError(StringerrorText) {//do stuff    }}

@CustomView example:

@CustomView(presenter =MyPresenter.class)publicclassMyCustomViewextendsViewimplementsMyView {@PresenterMyPresenterpresenter;@OverrideprotectedvoidonAttachedToWindow() {super.onAttachedToWindow();// Now presenter is injected.    }@OverridepublicvoidshowResult(StringresultText) {//do stuff    }@OverridepublicvoidshowError(StringerrorText) {//do stuff    }}

Injecting with Dagger

@Presenter annotation will instantiate your presenter class by calling its default constructor, So you can't pass any objects to the constructor.

But if you are usingDagger, you can use its constructor injection feature to inject your presenter.

So what you need is make your presenter injectable and add@Inject annotation before@Presenter. Here is an example:

publicclassMyPresenterextendsAbstractPresenter<MyView> {@InjectpublicMyPresenter(UseCase1useCase1,UseCase2useCase2){        }}@ActivityView(layout =R.layout.my_activity,presenter =MyPresenter.class)publicclassMyActivityextendsAppCompatActivityimplementsMyView {@Inject@PresenterMyPresenterpresenter;@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {SomeDaggerComponent.injectTo(this);super.onCreate(savedInstanceState);     }//...}

Don't inject dependencies aftersuper.onCreate(savedInstanceState); in activities,super.onActivityCreated(bundle); in fragments andsuper.onAttachedToWindow(); in custom views.

Clean Architecture Usage

You can follow the principles ofClean Architecture by applying 'easymvp-rx' plugin. Previous part was all about the presentation-layer, Now lets talk about the domain-layer.

Domain Layer holds all your business logic, it encapsulates and implements all of the use cases of the system.This layer is a pure java module without any android SDK dependencies.

UseCase

UseCases are the entry points to the domain layer. These use cases represent all the possible actions a developer can perform from the presentation layer.

Each use case should run off the main thread(UI thread), to avoid reinventing the wheel, EasyMVP uses RxJava to achieve this.

You can create a use case class by extending of the following classes:

publicclassSuggestPlacesextendsObservableUseCase<List<Place>,String> {privatefinalSearchRepositorysearchRepository;publicSuggestPlaces(SearchRepositorysearchRepository,UseCaseExecutoruseCaseExecutor,PostExecutionThreadpostExecutionThread) {super(useCaseExecutor,postExecutionThread);this.searchRepository =searchRepository;    }@OverrideprotectedObservable<List<Place>>interact(@NonNullStringquery) {returnsearchRepository.suggestPlacesByName(query);    }}
publicclassInstallThemeextendsCompletableUseCase<File> {privatefinalThemeManagerthemeManager;privatefinalFileManagerfileManager;publicInstallTheme(ThemeManagerthemeManager,FileManagerfileManager,UseCaseExecutoruseCaseExecutor,PostExecutionThreadpostExecutionThread) {super(useCaseExecutor,postExecutionThread);this.themeManager =themeManager;this.fileManager =fileManager;    }@OverrideprotectedCompletableinteract(@NonNullFilethemePath) {returnthemeManager.install(themePath)                .andThen(fileManager.remove(themePath))                .toCompletable();    }}

And the implementations ofUseCaseExecutor andPostExecutionThread are:

publicclassUIThreadimplementsPostExecutionThread {@OverridepublicSchedulergetScheduler() {returnAndroidSchedulers.mainThread();    }}publicclassBackgroundThreadimplementsUseCaseExecutor {@OverridepublicSchedulergetScheduler() {returnSchedulers.io();    }}

DataMapper

EachDataMapper transforms entities from the format most convenient for the use cases, to the format most convenient for the presentation layer.

But, why is it useful?

Let's seeSuggestPlaces use case again. Assume that you passed theMon query to this use case and it emitted:

  • Montreal
  • Monterrey
  • Montpellier

But you want to bold theMon part of each suggestion like:

  • Montreal
  • Monterrey
  • Montpellier

So, you can use a data mapper to transform thePlace object to the format most convenient for your presentation layer.

publicclassPlaceSuggestionMapperextendsDataMapper<List<SuggestedPlace>,List<Place>> {@OverridepublicList<SuggestedPlace>call(List<Place>places) {//TODO for each Place object, use SpannableStringBuilder to make a partial bold effect    }}

Note thatPlace entity lives in the domain layer butSuggestedPlace entity lives in the presentation layer.

So, How to bindDataMapper toObservableUseCase?

publicclassMyPresenterextendsRxPresenter<MyView> {privateSuggestPlacesuggestPlace;privateSuggestPlaceMappersuggestPlaceMapper;@InjectpublicMyPresenter(SuggestPlacesuggestPlace,SuggestPlaceMappersuggestPlaceMapper){this.suggestPlace =suggestPlace;this.suggestPlaceMapper =suggestPlaceMapper;    }voidsuggestPlaces(Stringquery){addSubscription(suggestPlace.execute(query)                                     .map(suggetsPlaceMapper)                                     .subscribe(suggestedPlaces->{//do-stuff                                      })                        );    }}

FAQ

How does EasyMVP work under the hood?

  • For each annotated class with@ActivityView,@FragmentView or@CustomView, EasyMVP generates*_ViewDelegate class in the same package. These classes are responsible for binding presenter's lifecycle.
  • EasyMVP uses bytecode weaving to call delegate classes inside your view implementation classes. You can find these manipulated classes inbuild/weaver folder.

Is there any restrictions on using EasyMVP?

Does it support kotlin?

  • Yes, See thisissue for details.

Documentations

EasyMVPAPI: Javadocs for the current API release

EasyMVPRX-API: Javadocs for the current RX-API (Clean Architecture API) release

EasyMVPRX2-API: Javadocs for the current RX2-API (Clean Architecture API) release

Demo

CleanTvMaze Shows how to use EasyMVP with Kotlin

TVProgram_Android Shows how to use EasyMVP with Java

Author

Saeid Masoumihajiagha

License

Copyright 2016-2017 6thSolution Technologies Inc.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at   http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

About

A full-featured framework that allows building android applications following the principles of Clean Architecture.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp