SlideShare a Scribd company logo
1 of 42
Sexy Architecting
VIPER: MVP on steroids
Dmytro Zaitsev
Mobile Team Lead
MVP/MVC/MVVM is NOT an
Architecture!
It’s only responsible for the presentation layer delivery mechanism
Real-world Android app
● Hard to understand
● Hard to maintain
● The business logic is mixed in Activity/Fragment
● High coupled components
● MVC -> Massive View Controllers
● Hard and often impossible to test
Clean Architecture
● Independent of Frameworks
● Testable
● Independent of Database
● Independent of any external agency
● Independent of UI
“
The Web is an I/O Device!
-Robert Martin
What is VIPER?
● A way of architecting applications which takes heavy inspiration from the
Clean Architecture
● Divides an app’s logical structure into distinct layers of responsibility
● Makes it easier to isolate dependencies
● Makes it easier test the interactions at the boundaries between layers
● Eliminates Massive View Controllers
Main parts of VIPER
● View
● Interactor
● Presenter
● Entity
● Router
View
Displays what it is told to by the Presenter and relays user input back
to the Presenter
View
● Is passive
● Waits for the Presenter to give it content to display
● Never asks the Presenter for data
● Determines how the content is displayed
● Handles user interaction and input
● Simply delegates user’s actions to the Presenter
● Awaits for a response telling it what should be displayed next
internal interface CheeseViewCallbacks {
fun onNewCheese(cheese: Collection<CheeseViewModel>)
fun showError()
fun hideProgress()
fun showProgress()
}
Example of View
class CheeseView : ConstraintLayout, CheeseViewCallbacks {
@Inject internal lateinit var presenter: CheesePresenter
private lateinit var progressDialog : ProgressDialog
private lateinit var adapter : CheeseAdapter
/** ... */
override fun onNewCheese(cheese: Collection<CheeseViewModel>) {
adapter.setModels(cheese)
adapter.notifyDataSetChanged()
}
override fun showError() {
Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show()
}
override fun hideProgress() = progressDialog.dismiss()
override fun showProgress() = progressDialog.show()
}
Example of View
Presenter
Contains view logic for preparing content for display (as received from
the Interactor) and for reacting to user inputs (by requesting new data
from the Interactor)
Presenter
● Knows about the content it maintains and when it should be displayed
● Receives input events coming from the View
● Applies view logic over this data to prepare the content
● Tells the View what to display
● Sends requests to an Interactor
● Works like a bridge between the main parts of a VIPER module
● Receives the data structures coming from the Interactor
● Knows when to navigate to another screen, and which screen to navigate to
class CheesePresenter(private val getCheeseInteractor: GetCheeseInteractor) {
var view: CheeseViewCallbacks? = null
var router: MainRouter? = null
/** ... */
fun fetchCheese(сount: Int) {
view?.showProgress()
getCheeseInteractor.execute({ cheese -> // onNext
view?.onNewCheese(cheese)
view?.hideProgress()
},
{ throwable -> // onError
view?.showError()
view?.hideProgress()
},
сount)
}
fun onItemClicked(model: CheeseViewModel) = router?.navigateToDetails(model)
}
Example of Presenter
Interactor
Contains the business logic as specified by a use case
Interactor
● Represents use cases
● Regular Java object
● No Android framework dependency
● Encapsulates application specific business rules
class GetCheeseInteractor @Inject constructor(
private val subscribeOn : Scheduler,
private val observeOn : Scheduler,
private val cheeseStorage: CheeseStorage) {
private val subscriptions = CompositeSubscription()
fun execute(subscriber: Subscriber<Collection<Cheese>>, сount: Int) {
subscriptions.add(cheeseStorage.getCheese(сount)
.subscribeOn(subscribeOn)
.observeOn(observeOn)
.subscribe(subscriber))
}
}
Example of Interactor
Entity
Contains basic model objects used by the Interactor
Entity
● POJOs
● Encapsulates different types of data
● Model objects manipulated by an Interactor
data class Cheese(
val id : Long,
val name : String,
val price : Long,
val description : String,
val type : String,
val texture : String,
val fatContent : String,
val animalMilk : String,
val regionOfOrigin: String
)
Example of Entity
Router
Contains navigation logic for describing which screens are shown in
which order
Router
● Responsible for passing data between screens
● Receives input commands from the Presenter
● Responsible for the navigation logic between modules
internal interface MainRouter {
fun navigateToDetails(model: CheeseViewModel)
fun navigateToPreferences()
fun navigateToRegistration()
}
Example of Router
class MainActivity : AppCompatActivity(), MainRouter {
override fun navigateToDetails(model: CheeseViewModel) {
startActivity(Intent(this, DetailsActivity::class.java).apply {
with(this) {
putExtra(DetailsActivity.NAME, model.name)
putExtra(DetailsActivity.CHECKED, model.isChecked)
}
})
}
override fun navigateToPreferences() {
startActivity(Intent(this, SettingsActivity::class.java))
}
override fun navigateToRegistration() {
supportFragmentManager.beginTransaction()
.replace(R.id.content, LoginFragment())
.commit()
}
}
Example of Router
Why should you use VIPER?
● It’s easier to track issues via crash reports
● The source code will be cleaner, more compact and reusable
● Adding new features is easier
● There are less conflicts with the rest of the development team
● It’s easier to write automated tests
When should you NOT use VIPER?
● It’s an overkill for small projects
● Causes an overhead when starting new projects
● MVP/MVC/MVVM-VIPER mix can cause headaches
● Lots of code all over the project
Testing
● Presentation layer
○ Espresso, Robolectric
● Domain layer
○ JUnit, TestNG, Mockito, PowerMock
● Data layer
○ Robolectric, JUnit, TestNG, Mockito, PowerMock
References
● http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/
● http://www.mttnow.com/blog/architecting-mobile-apps-with-bviper-modules
● http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/
● http://fernandocejas.com/2015/07/18/architecting-android-the-evolution/
● https://www.objc.io/issues/13-architecture/viper/
● https://github.com/RxViper/RxViper
● https://www.ckl.io/blog/ios-project-architecture-using-viper/
● http://luboganev.github.io/post/clean-architecture-pt2/
Thank you!
Questions?
Dmytro Zaitsev
@DmitriyZaitsev

More Related Content

What's hot

MVVM Light Toolkit Works Great, Less Complicated
MVVM Light ToolkitWorks Great, Less ComplicatedMVVM Light ToolkitWorks Great, Less Complicated
MVVM Light Toolkit Works Great, Less Complicated
mdc11
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
David Xi Peng Yang
 

What's hot (20)

AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.js
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Introduction to react js
Introduction to react jsIntroduction to react js
Introduction to react js
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
React JS .NET
React JS .NETReact JS .NET
React JS .NET
 
Brief intro 2 to angular 2
Brief intro 2 to angular 2Brief intro 2 to angular 2
Brief intro 2 to angular 2
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET Internals
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
MVVM Light Toolkit Works Great, Less Complicated
MVVM Light ToolkitWorks Great, Less ComplicatedMVVM Light ToolkitWorks Great, Less Complicated
MVVM Light Toolkit Works Great, Less Complicated
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
 
Flux architecture
Flux architectureFlux architecture
Flux architecture
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
 

Viewers also liked

3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 

Viewers also liked (20)

VIPER - Design Pattern
VIPER - Design PatternVIPER - Design Pattern
VIPER - Design Pattern
 
Rambler.iOS #5: VIPER a la Rambler
Rambler.iOS #5: VIPER a la RamblerRambler.iOS #5: VIPER a la Rambler
Rambler.iOS #5: VIPER a la Rambler
 
Rambler.iOS #5: VIPER и Swift
Rambler.iOS #5: VIPER и SwiftRambler.iOS #5: VIPER и Swift
Rambler.iOS #5: VIPER и Swift
 
Fun with Flows - Terry Cole
Fun with Flows - Terry ColeFun with Flows - Terry Cole
Fun with Flows - Terry Cole
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPERRambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
Rambler.iOS #5: Генерамба и прочие аспекты кодогенерации в VIPER
 
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
ReactiveCocoa: делаем отзывчивое приложение (П. Руденко)
 
[SIP 2015] iOS Proposal: VIPER
[SIP 2015] iOS Proposal: VIPER[SIP 2015] iOS Proposal: VIPER
[SIP 2015] iOS Proposal: VIPER
 
Viper - чистая архитектура iOS-приложения (И. Чирков)
Viper - чистая архитектура iOS-приложения (И. Чирков)Viper - чистая архитектура iOS-приложения (И. Чирков)
Viper - чистая архитектура iOS-приложения (И. Чирков)
 
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис ЛебедевВстреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
Встреча №9. Будущее паттерна MVVM в iOS приложениях, Денис Лебедев
 
iOS viper presentation
iOS viper presentationiOS viper presentation
iOS viper presentation
 
Architecting ASP.NET MVC Applications
Architecting ASP.NET MVC ApplicationsArchitecting ASP.NET MVC Applications
Architecting ASP.NET MVC Applications
 
MVP Clean Architecture
MVP Clean  Architecture MVP Clean  Architecture
MVP Clean Architecture
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
 
Design thinking. Principles and methods to go beyond UX.
Design thinking. Principles and methods to go beyond UX.Design thinking. Principles and methods to go beyond UX.
Design thinking. Principles and methods to go beyond UX.
 
Big Data World
Big Data WorldBig Data World
Big Data World
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
 

Similar to Sexy Architecting. VIPER: MVP on steroids

Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
Mahmoud Hamed Mahmoud
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
FIWARE
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
Alessandro Molina
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
Fermin Galan
 
A Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on AndroidA Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on Android
Outware Mobile
 

Similar to Sexy Architecting. VIPER: MVP on steroids (20)

Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Android development
Android developmentAndroid development
Android development
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Co
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows Phone
 
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
 
Conductor vs Fragments
Conductor vs FragmentsConductor vs Fragments
Conductor vs Fragments
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
 
Model View Presenter
Model View Presenter Model View Presenter
Model View Presenter
 
Do iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architecturesDo iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architectures
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
A Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on AndroidA Separation of Concerns: Clean Architecture on Android
A Separation of Concerns: Clean Architecture on Android
 
Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019
 

Recently uploaded

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 

Recently uploaded (20)

HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 

Sexy Architecting. VIPER: MVP on steroids

  • 1. Sexy Architecting VIPER: MVP on steroids Dmytro Zaitsev Mobile Team Lead
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. MVP/MVC/MVVM is NOT an Architecture! It’s only responsible for the presentation layer delivery mechanism
  • 9. Real-world Android app ● Hard to understand ● Hard to maintain ● The business logic is mixed in Activity/Fragment ● High coupled components ● MVC -> Massive View Controllers ● Hard and often impossible to test
  • 10.
  • 11. Clean Architecture ● Independent of Frameworks ● Testable ● Independent of Database ● Independent of any external agency ● Independent of UI
  • 12. “ The Web is an I/O Device! -Robert Martin
  • 13.
  • 14.
  • 15. What is VIPER? ● A way of architecting applications which takes heavy inspiration from the Clean Architecture ● Divides an app’s logical structure into distinct layers of responsibility ● Makes it easier to isolate dependencies ● Makes it easier test the interactions at the boundaries between layers ● Eliminates Massive View Controllers
  • 16. Main parts of VIPER ● View ● Interactor ● Presenter ● Entity ● Router
  • 17.
  • 18. View Displays what it is told to by the Presenter and relays user input back to the Presenter
  • 19. View ● Is passive ● Waits for the Presenter to give it content to display ● Never asks the Presenter for data ● Determines how the content is displayed ● Handles user interaction and input ● Simply delegates user’s actions to the Presenter ● Awaits for a response telling it what should be displayed next
  • 20. internal interface CheeseViewCallbacks { fun onNewCheese(cheese: Collection<CheeseViewModel>) fun showError() fun hideProgress() fun showProgress() } Example of View
  • 21.
  • 22. class CheeseView : ConstraintLayout, CheeseViewCallbacks { @Inject internal lateinit var presenter: CheesePresenter private lateinit var progressDialog : ProgressDialog private lateinit var adapter : CheeseAdapter /** ... */ override fun onNewCheese(cheese: Collection<CheeseViewModel>) { adapter.setModels(cheese) adapter.notifyDataSetChanged() } override fun showError() { Toast.makeText(context, R.string.error, Toast.LENGTH_SHORT).show() } override fun hideProgress() = progressDialog.dismiss() override fun showProgress() = progressDialog.show() } Example of View
  • 23. Presenter Contains view logic for preparing content for display (as received from the Interactor) and for reacting to user inputs (by requesting new data from the Interactor)
  • 24. Presenter ● Knows about the content it maintains and when it should be displayed ● Receives input events coming from the View ● Applies view logic over this data to prepare the content ● Tells the View what to display ● Sends requests to an Interactor ● Works like a bridge between the main parts of a VIPER module ● Receives the data structures coming from the Interactor ● Knows when to navigate to another screen, and which screen to navigate to
  • 25. class CheesePresenter(private val getCheeseInteractor: GetCheeseInteractor) { var view: CheeseViewCallbacks? = null var router: MainRouter? = null /** ... */ fun fetchCheese(сount: Int) { view?.showProgress() getCheeseInteractor.execute({ cheese -> // onNext view?.onNewCheese(cheese) view?.hideProgress() }, { throwable -> // onError view?.showError() view?.hideProgress() }, сount) } fun onItemClicked(model: CheeseViewModel) = router?.navigateToDetails(model) } Example of Presenter
  • 26. Interactor Contains the business logic as specified by a use case
  • 27. Interactor ● Represents use cases ● Regular Java object ● No Android framework dependency ● Encapsulates application specific business rules
  • 28. class GetCheeseInteractor @Inject constructor( private val subscribeOn : Scheduler, private val observeOn : Scheduler, private val cheeseStorage: CheeseStorage) { private val subscriptions = CompositeSubscription() fun execute(subscriber: Subscriber<Collection<Cheese>>, сount: Int) { subscriptions.add(cheeseStorage.getCheese(сount) .subscribeOn(subscribeOn) .observeOn(observeOn) .subscribe(subscriber)) } } Example of Interactor
  • 29. Entity Contains basic model objects used by the Interactor
  • 30. Entity ● POJOs ● Encapsulates different types of data ● Model objects manipulated by an Interactor
  • 31. data class Cheese( val id : Long, val name : String, val price : Long, val description : String, val type : String, val texture : String, val fatContent : String, val animalMilk : String, val regionOfOrigin: String ) Example of Entity
  • 32. Router Contains navigation logic for describing which screens are shown in which order
  • 33.
  • 34.
  • 35. Router ● Responsible for passing data between screens ● Receives input commands from the Presenter ● Responsible for the navigation logic between modules
  • 36. internal interface MainRouter { fun navigateToDetails(model: CheeseViewModel) fun navigateToPreferences() fun navigateToRegistration() } Example of Router
  • 37. class MainActivity : AppCompatActivity(), MainRouter { override fun navigateToDetails(model: CheeseViewModel) { startActivity(Intent(this, DetailsActivity::class.java).apply { with(this) { putExtra(DetailsActivity.NAME, model.name) putExtra(DetailsActivity.CHECKED, model.isChecked) } }) } override fun navigateToPreferences() { startActivity(Intent(this, SettingsActivity::class.java)) } override fun navigateToRegistration() { supportFragmentManager.beginTransaction() .replace(R.id.content, LoginFragment()) .commit() } } Example of Router
  • 38. Why should you use VIPER? ● It’s easier to track issues via crash reports ● The source code will be cleaner, more compact and reusable ● Adding new features is easier ● There are less conflicts with the rest of the development team ● It’s easier to write automated tests
  • 39. When should you NOT use VIPER? ● It’s an overkill for small projects ● Causes an overhead when starting new projects ● MVP/MVC/MVVM-VIPER mix can cause headaches ● Lots of code all over the project
  • 40. Testing ● Presentation layer ○ Espresso, Robolectric ● Domain layer ○ JUnit, TestNG, Mockito, PowerMock ● Data layer ○ Robolectric, JUnit, TestNG, Mockito, PowerMock
  • 41. References ● http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/ ● http://www.mttnow.com/blog/architecting-mobile-apps-with-bviper-modules ● http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/ ● http://fernandocejas.com/2015/07/18/architecting-android-the-evolution/ ● https://www.objc.io/issues/13-architecture/viper/ ● https://github.com/RxViper/RxViper ● https://www.ckl.io/blog/ios-project-architecture-using-viper/ ● http://luboganev.github.io/post/clean-architecture-pt2/