SlideShare a Scribd company logo
1 of 43
Download to read offline
VIPER
Make your MVP cleaner
Dmytro Zaitsev
Senior Mobile Developer @ Lóhika
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(amount: Int) {
view?.showProgress()
getCheeseInteractor.execute({ cheese -> // onNext
view?.onNewCheeses(cheese)
view?.hideProgress()
},
{ // onError
view?.showError()
view?.hideProgress()
},
amount)
}
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>>,
amount : Int) {
subscriptions.add(cheeseStorage.getCheese(amount)
.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, Mockito, PowerMock
● Data layer
○ Robolectric, JUnit, 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/
Demo
Dmytro Zaitsev
@DmitriyZaitsev
Questions?
Thank you!

More Related Content

What's hot

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingMitinPavel
 
지금 당장 (유사) BDD 시작하기
지금 당장 (유사) BDD 시작하기지금 당장 (유사) BDD 시작하기
지금 당장 (유사) BDD 시작하기chanju Jeon
 

What's hot (6)

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
React hooks
React hooksReact hooks
React hooks
 
Max euro python 2015
Max euro python 2015Max euro python 2015
Max euro python 2015
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event Sourcing
 
지금 당장 (유사) BDD 시작하기
지금 당장 (유사) BDD 시작하기지금 당장 (유사) BDD 시작하기
지금 당장 (유사) BDD 시작하기
 

Viewers also liked

Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - Zvooq
Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - ZvooqDroidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - Zvooq
Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - ZvooqMail.ru Group
 
Event bus for android
Event bus for androidEvent bus for android
Event bus for android丞廷 鄭
 
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonMinicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonRicardo Longa
 
Half way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Half way to clean architecture - Dmytro Voronkevych - Droidcon BerlinHalf way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Half way to clean architecture - Dmytro Voronkevych - Droidcon BerlinBadoo
 
Five android architecture
Five android architectureFive android architecture
Five android architectureTomislav Homan
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshopJorge Ortiz
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h editionJorge Ortiz
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Androidgreenrobot
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroidHiroyuki Kusu
 
Android cleanarchitecture
Android cleanarchitectureAndroid cleanarchitecture
Android cleanarchitectureTomoaki Imai
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Svetlin Nakov
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsDmytro Zaitsev
 

Viewers also liked (15)

Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - Zvooq
Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - ZvooqDroidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - Zvooq
Droidcon Moscow 2015. Clean Architecture и MVP. Алексей Макаров - Zvooq
 
GreenRobot-Eventbus
GreenRobot-EventbusGreenRobot-Eventbus
GreenRobot-Eventbus
 
Event bus for android
Event bus for androidEvent bus for android
Event bus for android
 
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonMinicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
 
Half way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Half way to clean architecture - Dmytro Voronkevych - Droidcon BerlinHalf way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
Half way to clean architecture - Dmytro Voronkevych - Droidcon Berlin
 
"Clean" Architecture
"Clean" Architecture"Clean" Architecture
"Clean" Architecture
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshop
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h edition
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid【Potatotips #26】Replace EventBus with RxJava/RxAndroid
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
 
MVP Clean Architecture
MVP Clean  Architecture MVP Clean  Architecture
MVP Clean Architecture
 
Android cleanarchitecture
Android cleanarchitectureAndroid cleanarchitecture
Android cleanarchitecture
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
Sexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroidsSexy Architecting. VIPER: MVP on steroids
Sexy Architecting. VIPER: MVP on steroids
 

Similar to VIPER Make your MVP cleaner

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 Patterngoodfriday
 
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
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Patternmaddinapudi
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneVincent Hoogendoorn
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
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 2019iFour Technolab Pvt. Ltd.
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Alessandro Molina
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Coe-Legion
 
Model View Presenter
Model View Presenter Model View Presenter
Model View Presenter rendra toro
 
Do iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architecturesDo iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architecturesDavid Broža
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB
 
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 AndroidOutware Mobile
 
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-WAREFermin Galan
 
Portlets 2.0 Tssjs Prague 2008
Portlets 2.0 Tssjs Prague 2008Portlets 2.0 Tssjs Prague 2008
Portlets 2.0 Tssjs Prague 2008SteveMillidge
 
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 2019UA Mobile
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 

Similar to VIPER Make your MVP cleaner (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
 
MvvmQuickCross for Windows Phone
MvvmQuickCross for Windows PhoneMvvmQuickCross for Windows Phone
MvvmQuickCross for Windows Phone
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Android development
Android developmentAndroid development
Android development
 
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
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
 
Conductor vs Fragments
Conductor vs FragmentsConductor vs Fragments
Conductor vs Fragments
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Co
 
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
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
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
 
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
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Portlets 2.0 Tssjs Prague 2008
Portlets 2.0 Tssjs Prague 2008Portlets 2.0 Tssjs Prague 2008
Portlets 2.0 Tssjs Prague 2008
 
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
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 

More from Аліна Шепшелей

Vladimir Lozanov How to deliver high quality apps to the app store
Vladimir Lozanov	How to deliver high quality apps to the app storeVladimir Lozanov	How to deliver high quality apps to the app store
Vladimir Lozanov How to deliver high quality apps to the app storeАліна Шепшелей
 
Oleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile projectOleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile projectАліна Шепшелей
 
Alexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real worldAlexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real worldАліна Шепшелей
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Аліна Шепшелей
 
Valerii Iakovenko Drones as the part of the present
Valerii Iakovenko	Drones as the part of the presentValerii Iakovenko	Drones as the part of the present
Valerii Iakovenko Drones as the part of the presentАліна Шепшелей
 
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...Аліна Шепшелей
 
Anton Ivinskyi Application level metrics and performance tests
Anton Ivinskyi	Application level metrics and performance testsAnton Ivinskyi	Application level metrics and performance tests
Anton Ivinskyi Application level metrics and performance testsАліна Шепшелей
 
Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?Аліна Шепшелей
 
Макс Семенчук Дизайнер, которому доверяют
 Макс Семенчук Дизайнер, которому доверяют Макс Семенчук Дизайнер, которому доверяют
Макс Семенчук Дизайнер, которому доверяютАліна Шепшелей
 
Anton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designersAnton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designersАліна Шепшелей
 
Andrew Veles Product design is about the process
Andrew Veles Product design is about the processAndrew Veles Product design is about the process
Andrew Veles Product design is about the processАліна Шепшелей
 
Kononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TVKononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TVАліна Шепшелей
 
Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?Аліна Шепшелей
 
Gregory Shehet Undefined' on prod, or how to test a react app
Gregory Shehet Undefined' on  prod, or how to test a react appGregory Shehet Undefined' on  prod, or how to test a react app
Gregory Shehet Undefined' on prod, or how to test a react appАліна Шепшелей
 
Alexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programmingAlexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programmingАліна Шепшелей
 
Roman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your dbRoman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your dbАліна Шепшелей
 

More from Аліна Шепшелей (20)

Vladimir Lozanov How to deliver high quality apps to the app store
Vladimir Lozanov	How to deliver high quality apps to the app storeVladimir Lozanov	How to deliver high quality apps to the app store
Vladimir Lozanov How to deliver high quality apps to the app store
 
Oleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile projectOleksandr Yefremov Continuously delivering mobile project
Oleksandr Yefremov Continuously delivering mobile project
 
Alexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real worldAlexander Voronov Test driven development in real world
Alexander Voronov Test driven development in real world
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
Valerii Iakovenko Drones as the part of the present
Valerii Iakovenko	Drones as the part of the presentValerii Iakovenko	Drones as the part of the present
Valerii Iakovenko Drones as the part of the present
 
Valerii Moisieienko Apache hbase workshop
Valerii Moisieienko	Apache hbase workshopValerii Moisieienko	Apache hbase workshop
Valerii Moisieienko Apache hbase workshop
 
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
Dmitriy Kouperman Working with legacy systems. stabilization, monitoring, man...
 
Anton Ivinskyi Application level metrics and performance tests
Anton Ivinskyi	Application level metrics and performance testsAnton Ivinskyi	Application level metrics and performance tests
Anton Ivinskyi Application level metrics and performance tests
 
Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?Миша Рыбачук Что такое дизайн?
Миша Рыбачук Что такое дизайн?
 
Макс Семенчук Дизайнер, которому доверяют
 Макс Семенчук Дизайнер, которому доверяют Макс Семенчук Дизайнер, которому доверяют
Макс Семенчук Дизайнер, которому доверяют
 
Anton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designersAnton Parkhomenko Boost your design workflow or git rebase for designers
Anton Parkhomenko Boost your design workflow or git rebase for designers
 
Andrew Veles Product design is about the process
Andrew Veles Product design is about the processAndrew Veles Product design is about the process
Andrew Veles Product design is about the process
 
Kononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TVKononenko Alina Designing for Apple Watch and Apple TV
Kononenko Alina Designing for Apple Watch and Apple TV
 
Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?Mihail Patalaha Aso: how to start and how to finish?
Mihail Patalaha Aso: how to start and how to finish?
 
Gregory Shehet Undefined' on prod, or how to test a react app
Gregory Shehet Undefined' on  prod, or how to test a react appGregory Shehet Undefined' on  prod, or how to test a react app
Gregory Shehet Undefined' on prod, or how to test a react app
 
Alexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programmingAlexey Osipenko Basics of functional reactive programming
Alexey Osipenko Basics of functional reactive programming
 
Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web Vladimir Mikhel Scrapping the web
Vladimir Mikhel Scrapping the web
 
Roman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your dbRoman Ugolnikov Migrationа and sourcecontrol for your db
Roman Ugolnikov Migrationа and sourcecontrol for your db
 
Dmutro Panin JHipster
Dmutro Panin JHipster Dmutro Panin JHipster
Dmutro Panin JHipster
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 

VIPER Make your MVP cleaner

  • 1. VIPER Make your MVP cleaner Dmytro Zaitsev Senior Mobile Developer @ Lóhika
  • 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(amount: Int) { view?.showProgress() getCheeseInteractor.execute({ cheese -> // onNext view?.onNewCheeses(cheese) view?.hideProgress() }, { // onError view?.showError() view?.hideProgress() }, amount) } 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>>, amount : Int) { subscriptions.add(cheeseStorage.getCheese(amount) .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, Mockito, PowerMock ● Data layer ○ Robolectric, JUnit, 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/
  • 42. Demo