MVVM vs. MVI - Understand the Difference Once and for All

Philipp Lackner
17 Apr 202418:40

Summary

TLDRВ этом видео сравниваются два популярных шаблона архитектуры приложений: MVVM и MVI. Автор объясняет, что оба шаблона предназначены для разделения представления, но не для всей приложения. Он демонстрирует, как реализовать каждый из шаблонов в Android, используя примеры кода и объясняя ключевые различия. В видео также упоминается бесплатный онлайн-семинар для Android-разработчиков, который будет посвящён основным практикам и архитектурным шаблонам. В заключение автор рекомендует попробовать оба шаблона и выбрать тот, который больше всего подходит для команды и проекта.

Takeaways

  • 📚 В видео обсуждается различие между архитектурными шаблонами MVVM и MVI в разработке нативного Android.
  • 🔍 MVVM (Model-View-ViewModel) и MVI (Model-View-Intent) являются представлениями шаблонов и используются для разделения представления слоя в приложении.
  • 🏗️ Оба шаблона не предназначены для разделения всей приложения на части, а только для представления слоя, в отличие от Clean Architecture, который разделяет все приложение на слои.
  • 📈 Важно понимать, что модель в обоих шаблонах отвечает за бизнес-логику и правила, часто представленные в виде обычных классов данных.
  • 🎭 Представление (View) обозначает то, что видно пользователю, и может быть реализовано как XML-шаблоны, классы представлений или композиции Jetpack Compose.
  • 🧐 ViewModel в MVVM и ViewModel в MVI оба отвечают за логику состояния, определяя, как должно выглядеть состояние после пользовательских действий.
  • 🔑 Основное различие между MVVM и MVI заключается в использовании MVI(Intent) для группировки пользовательских намерений на экране в одно действие.
  • 🤔 MVI использует единый класс состояния (UI State), в то время как MVVM может иметь множество полей состояния для разных компонентов UI.
  • 🛠️ В MVI для обработки действий предоставляется функция onAction, что позволяет обрабатывать различные пользовательские намерения (например, переключение лайка).
  • ⚠️ Критики MVI указывают на дополнительный слой (Intent) и возможные проблемы с производительностью при обновлении состояния, в отличие от MVVM.
  • 📉 Несмотря на возможные недостатки, MVI считается более читаемым и простым в использовании, особенно для больших экранов с множеством состояний.

Q & A

  • Что означает аббревиатура MVVM в контексте разработки на Android?

    -MVVM означает Model-View-ViewModel. Это архитектурный шаблон, используемый для разделения представления (View) и бизнес-логики (Model) с помощью ViewModel, который работает как связующий элемент между ними.

  • Какова разница между MVVM и MVI в разработке на Android?

    -В MVI (Model-View-Intent), в отличие от MVVM, представление (View) отправляет 'намерения' (Intent) в ViewModel, который затем обрабатывает эти намерения и обновляет состояние. В MVVM состояние обновляется непосредственно в ViewModel в ответ на действия пользователя.

  • Почему разработчики иногда предпочитают MVVM перед MVI?

    -Разработчики могут предпочесть MVVM из-за его простоты и того, что он предлагает прямую связь между действиями пользователя и изменениями состояния, что может быть проще для понимания и реализации.

  • Что такое 'намерение' (Intent) в контексте MVI?

    -Намерение в MVI - это действие пользователя, которое представление (View) отправляет в ViewModel. Это может быть, например, нажатие кнопки или изменение текста в поле ввода.

  • Какие преимущества предлагает использование MVI в сравнении с MVVM?

    -MVI может предоставить более чистую и понятную структуру кода благодаря группировке всех состояний в одном классе и использованию намерений для обработки действий пользователя.

  • Какие могут быть недостатки использования MVI?

    -Одним из недостатков MVI может быть то, что при больших экранах может быть необходимо обрабатывать много различных намерений, что может усложнить код и сделать его менее читабельным.

  • Что такое ViewModel в Android и как он используется в MVVM и MVI?

    -ViewModel в Android - это компонент, который хранит состояние приложения и используется для связи между моделью (Model) и представлением (View). В MVVM ViewModel обрабатывает действия и обновляет состояние, в то время как в MVI он обрабатывает намерения, отправленные View.

  • Какие типы данных используются для представления бизнес-правил и логики в модели MVVM и MVI?

    -Для представления бизнес-правил и логики в модели MVVM и MVI обычно используются обычные классы данных (data classes), которые содержат информацию о том, какие данные и какая логика необходимы для работы приложения.

  • Какие существуют альтернативы MVVM и MVI в архитектуре приложения?

    -Альтернативы MVVM и MVI включают в себя, например, Clean Architecture, которая разделяет приложение на несколько слоев, включая домен, представление и ввод-вывод.

  • Какие дополнительные ресурсы предлагает автор для изучения MVVM и MVI?

    -Автор предлагает участие в бесплатной онлайн-работе, которая будет посвящена основным темам для Android-разработчиков, включая архитектурные шаблоны, такие как MVVM и MVI.

Outlines

00:00

📚 Введение в MVVM и MVI

В этом параграфе представитель разработки Android-приложений вступает в дискуссию о двух популярных архитектурных шаблонах: MVVM и MVI. Он заметает, что многие разработчики выбирают один из шаблонов без полного понимания их различий и преимуществ. Автор видео обещает провести сравнение MVVM (Model-View-ViewModel) и MVI (Model-View-Intent), чтобы зрители могли определить, какой из шаблонов подходит лучше для их проектов. Также упоминается ожидаемое большое объявление проекта, посвящённого основам разработки Android, и бесплатный онлайн-семинар, который будет проведен 27 апреля.

05:00

🔍 Общие черты MVVM и MVI

Автор объясняет, что оба шаблона являются представлением шаблонов и предназначены для разделения слоя представления в приложении. Он уточняет, что эти шаблоны не должны путаться с другими, такими как Clean Architecture, и что они относятся только к части приложения, отвечающей за представление данных. В этом параграфе также определяются термины 'модель' и 'представление', которые являются общими для обоих шаблонов, и рассматривается их роль в реализации бизнес-логики и структуры данных приложения.

10:02

🛠 Различия между MVVM и MVI

В этом разделе видео скрипта подчёркивается, что основное различие между MVVM и MVI заключается в подходе к обработке пользовательских действий и состояния UI. В MVVM используется ViewModel, который содержит логику состояния, в то время как в MVI - ViewModel обрабатывает 'намерения' пользователя, определяя, как должно изменяться состояние приложения в ответ на действия пользователя. Автор предоставляет примеры реализации обоих шаблонов на Android, демонстрируя, как они могут быть использованы в одном проекте, и объясняя ключевые различия в их структуре и использовании.

15:04

🤔 Выбор между MVVM и MVI

Автор завершает видео, обсуждая преимущества и недостатки обоих шаблонов. Он подчёркивает, что выбор между MVVM и MVI должен быть основан на личных предпочтениях и потребностях команды разработки. Автор не рекомендует 'религиозное' следование какому-либо шаблону, а скорее предлагает попробовать оба и выбрать то, что лучше всего подходит для конкретного проекта. Также упоминается, что важно обеспечить единообразие в использовании выбранного шаблона в команде для эффективного и последовательного разработки.

Mindmap

Keywords

💡MVVM

MVVM (Model-View-ViewModel) - это архитектурный шаблон проектирования, который используется в разработке приложений. В контексте видео, это означает разделение приложения на три слоя: модель, представление и представленный модельный слой. Модель содержит бизнес-логику, представление отвечает за взаимодействие с пользователем, а ViewModel связывает их, обеспечивая независимость представления от модели. Пример из скрипта: 'the terms mvvm and mvi', где обсуждается выбор между шаблонами MVVM и MVI.

💡MVI

MVI (Model-View-Intent) - это альтернативный архитектурный шаблон к MVVM, который также разделяет приложение на слои, но использует дополнительный слой(Intent) для представления пользовательских действий. В видео это связано с обсуждением различий в реализации ViewModel и обработки пользовательских действий. Пример: 'mvi is the best pattern', где рассматривается предпочтительность шаблона MVI для определенных типов приложений.

💡архитектурные шаблоны

Архитектурные шаблоны - это повторно используемые решения для распределения ответственности и структуры в программном обеспечении. В видео они важны для выбора подходящего метода организации кода и логики приложения. Пример: 'compare these patterns', где видео намеревается сравнить MVVM и MVI.

💡ViewModel

ViewModel в архитектурных шаблонах MVVM и MVI - это компонент, отвечающий за логику и состояние приложения, отделенное от представления. Он связан с моделью и предоставляет данные для отображения. В видео ViewModel обсуждается в контексте обработки состояния и действий пользователя. Пример: 'the term view model is contained in the abbreviation', где ViewModel связан с реализацией шаблона MVVM.

💡Model

Model в контексте MVVM и MVI - это компонент, реализующий бизнес-правила и логику приложения. Он содержит данные и бизнес-правила, необходимые для функционирования приложения. В видео модель описывается как 'implements the business rules' и связана с типами данных, такими как 'Post', 'User' и 'Comment'.

💡View

View в архитектурных шаблонах - это пользовательский интерфейс, отвечающий за взаимодействие с пользователем. В Android это могут быть XML-разметки или классы представлений. В видео View обсуждается в контексте того, как шаблоны MVVM и MVI разделяют представление на отдельные части. Пример: 'the view in the end just refers to what's visible to the user'.

💡Intent

Intent в архитектурном шаблоне MVI - это компонент, который представляет пользовательские действия или намерения. Он используется для обработки различных действий пользователя в представлении. В видео Intent связан с обсуждением реализации пользовательских действий в MVI. Пример: 'model view intent', где подчеркивается важность намерений в архитектуре MVI.

💡State

State в контексте ViewModel - это состояние приложения, которое может включать в себя различные данные, такие как флаги загрузки, значения полей ввода и т.д. В видео State обсуждается как часть ViewModel, который обрабатывает и изменяет состояние в ответ на действия пользователя. Пример: 'the job of the view model is to contain the state mapping logic'.

💡Reactivity

Reactivity - это концепция, позволяющая систематизировать изменения состояния в ответ на действия пользователя. В видео реактивность связана с обсуждением того, как ViewModel может реагировать на изменения в данных, таких как поле ввода email. Пример: 'you can implement this reactivity much better with single states', где реактивность используется для обновления состояния в реальном времени.

💡Jetpack Compose

Jetpack Compose - это фреймворк для создания пользовательского интерфейса в Android, который использует Kotlin для декларативного определения UI. В видео Compose упоминается в контексте реализации представлений в шаблонах MVVM и MVI. Пример: 'if you're using jetpack, compos it would be the composable', где Compose используется для создания компонентов UI.

Highlights

Introduction to comparing MVVM and MVI patterns in Android development.

The importance of understanding the difference between MVVM and MVI to avoid blindly following ideologies.

MVVM and MVI are both presentational patterns, not full app architectural solutions.

Explanation of the term 'model' in MVVM and MVI, focusing on business rules and logic.

Clarification that the 'view' in both patterns refers to the UI visible to the user.

The role of the view model in containing state mapping logic in both patterns.

Practical examples of implementing MVVM and MVI in Android development.

The structural differences between MVVM and MVI, particularly in state management and intent handling.

MVI's approach to bundling user intentions into a single state object and action interface.

Critique of MVI's additional layer of intent, arguing for a simpler approach in MVVM.

Advantages of MVI for readability and ease of understanding screen state changes.

Performance considerations when using MVI with a single state class in reactive programming.

The flexibility of combining states in MVVM despite having multiple state fields.

Addressing criticisms of MVVM and MVI and providing counterarguments for each.

Recommendation to try both patterns and choose based on team preference and project needs.

Emphasis on not becoming religious about architectural design patterns and maintaining flexibility.

Invitation to a free live online workshop on essential topics for Android developers.

Conclusion and call to action for feedback on preferred patterns and learning outcomes from the video.

Transcripts

play00:00

hey guys and welcome back to a new video

play00:02

when learning about Native Android

play00:03

development you really don't get around

play00:06

the terms mvvm and mvi some people swear

play00:10

on using mvvm some other people say mvi

play00:12

is the best pattern for every type of

play00:14

app and I also have the feeling that

play00:15

most people don't even understand what

play00:17

the real difference is and then just

play00:19

blindly follow some ideologies from

play00:22

other developers so in this video I will

play00:23

really compare these patterns once and

play00:25

for all so you will know what is the

play00:27

same about those what are crucial

play00:29

differences and at the end you will be

play00:31

able to choose the right pattern for

play00:33

your project and all of that I will not

play00:35

just say straight into this camera but I

play00:36

will actually show you practical

play00:38

examples so you can see right away what

play00:40

those differences are just one thing

play00:42

before as you've maybe seen in the last

play00:44

video I am currently working on

play00:46

something really big on something that

play00:48

will teach you all those Essentials all

play00:50

those fundamental practices every

play00:52

Android developer out there has to know

play00:54

if you're aiming to have a place in the

play00:56

industry and on Saturday April 27th I

play00:58

will host a free live online Workshop in

play01:01

which I will share what all those

play01:03

essential topics are for Android

play01:04

developers so software engineering

play01:06

Essentials like architecture code style

play01:08

best practices but also those technical

play01:11

Essentials so those technical topics you

play01:13

have to know as a professional Android

play01:15

developer and then at the end of this

play01:17

Workshop I will reveal my big project

play01:19

Essentials so if you want to be part of

play01:20

this Workshop click the first link in

play01:22

this video's description and save your

play01:23

free spot but coming back to mvvm versus

play01:26

mvi let's first of all talk about what

play01:28

is actually the same about these pattern

play01:30

in the end both mvvm which stands for

play01:32

model view view model and mvi which

play01:34

stands for model view intent both these

play01:36

architectural design patterns are

play01:37

so-called presentational patterns and

play01:40

that's already the first thing most

play01:41

people don't know those patterns are

play01:43

only meant to separate your presentation

play01:45

layer in different parts they are not

play01:47

meant to separate your whole app into

play01:49

different parts because I often hear

play01:50

people talk about should I use mvvm or

play01:52

clean architecture no those are very

play01:55

different things you can use both in one

play01:57

project because clean architecture

play01:58

separates your whole app into different

play02:00

parts into different layers while MVM

play02:02

will only separate your presentation

play02:03

layer which is really only one part of a

play02:05

clean architecture project into

play02:07

different parts so now that we know what

play02:09

these two patterns stand for mvvm model

play02:11

view view model and mvi model view

play02:14

intent we can first of all think about

play02:16

the common terms that are included in

play02:18

both these patterns that is on the one

play02:20

hand model and view let's first of all

play02:22

understand what a model is because a

play02:24

model is a very broad term in the sense

play02:26

of software engineering and can refer to

play02:28

a lot while in the case of mvvm and mvi

play02:31

the model implements the business rules

play02:33

and business logic so that means they

play02:35

just Implement project-wide requirements

play02:37

and if we think of an app like a social

play02:39

network app where users have profiles

play02:41

where they can post something where they

play02:43

comment under posts then these are

play02:46

project right requirements that hey we

play02:47

want to have comments under post and

play02:50

these are the data types that a comment

play02:51

must have then these business rules will

play02:53

also tell you what a post actually is

play02:55

what does a post consist of is it just a

play02:57

text Does it include an image and in the

play02:59

end in cotland those are very often just

play03:01

normal data classes as we can see here

play03:03

we have a common data class and that

play03:04

just encodes the logic or the rules that

play03:07

make a comment model in the scope or in

play03:09

the domain of this specific social

play03:11

network project so we say Okay a comment

play03:13

definitely has an ID it has an author

play03:15

who wrote that comment which again is

play03:17

another model a user model which I will

play03:19

show you in a moment and it has some

play03:20

content in form of a string if you then

play03:22

take a look at the user model then you

play03:25

might see okay a user also has an ID a

play03:27

user has a username an email a specific

play03:29

role maybe which could be user or admin

play03:32

and then you can see such a business

play03:33

rule could also just be a function here

play03:35

part of such user class because whether

play03:37

a user is allowed to dedi a specific

play03:39

post that is very specific and that only

play03:42

gets clear from reading the requirements

play03:43

of the project so it's really specific

play03:45

to the domain of your project since in

play03:47

this case if you're an admin you can

play03:48

delete any post and if you're user you

play03:50

can only delete the post if your uh if

play03:52

the ID of the user is actually the same

play03:54

of the author so if the user is the

play03:56

author of the post then they can delete

play03:58

it and just for the sake of completeness

play03:59

we Al have a post model each post also

play04:01

has an author a Content an image URL a

play04:04

list of comments and a Boolean whether

play04:06

we like that post or not so that is

play04:08

already one part that is the same about

play04:10

mvvm and MBI now in Android we often

play04:13

work with a separate domain layer and

play04:15

the past one to two minutes I already

play04:16

mentioned the term domain quite often so

play04:19

in case you have such a domain layer the

play04:20

model is not strictly part of the

play04:23

presentation layer but rather of the

play04:24

separate domain layer but you don't have

play04:26

to work with such a domain layer and if

play04:28

you don't then the model is part of the

play04:29

presentation layer which is then part of

play04:31

either mvvm or mvi in this case all

play04:34

right so that's the model which is

play04:35

common between these two patterns then

play04:37

the so-called view is also common and

play04:39

the view in the end just refers to

play04:41

what's visible to the user so your

play04:43

actual UI and on Android that would

play04:44

either be your XML layout or the actual

play04:47

view class or if you're using jetpack

play04:49

compos it would be the composable so in

play04:51

the end both these patterns just try to

play04:53

separate your presentation layer into

play04:55

distinct parts so what's visible to the

play04:57

user where data comes from the model and

play05:00

one more thing in which these patterns

play05:02

now differ a little bit The View model

play05:04

so while in mvvm the term view model is

play05:06

contained in the abbreviation in MBI

play05:08

it's not because it stands for model

play05:10

view intent so there we have this intent

play05:12

yet on Android both these patterns are

play05:13

typically implemented with a view model

play05:15

pattern so the job of the view model is

play05:16

to contain the state mapping logic so

play05:19

that means it processes incoming UI

play05:21

actions like a button click like a

play05:23

refresh swipe and then decides based on

play05:25

these actions how the state needs to

play05:28

look like after these so if we swipe to

play05:30

refresh the view model has the job to

play05:31

decide okay now I need to show the

play05:33

loading indicator while we're actually

play05:35

refreshing after that I have to show the

play05:37

new items in the list so that way in the

play05:38

end we really have a dumb UI on the one

play05:40

hand which just takes in incoming State

play05:43

and decides what that state now means

play05:44

for the UI then we have the view model

play05:47

which decides how the state needs to be

play05:49

constructed and we have the model from

play05:51

where our business logic our business

play05:52

rules and all the data comes from so now

play05:55

that I've sat that the model The View

play05:57

and also the view model in most cases is

play05:59

the same between those two patterns

play06:01

what's really the difference and for

play06:02

that on the one hand I have prepared an

play06:03

example that shows you mvvm implemented

play06:06

with a single screen and also an example

play06:08

of mvi and that will really help us to

play06:10

understand the differences taking a look

play06:12

at our mvvm screen so here I have an MVM

play06:15

screen root composable which just takes

play06:17

in our nav controller and our view model

play06:20

reference and then forwards the states

play06:22

which are hosted from The View model to

play06:24

the actual screen composable that is

play06:26

just a common pattern I use that I have

play06:27

such a root composable and then the

play06:29

actual screen composable since if we

play06:31

would pass a normal view model to a real

play06:33

screen composable then that would break

play06:35

the preview since our preview is not

play06:37

able to construct view model references

play06:39

that have a Constructor so this type of

play06:41

structure with this root screen and this

play06:42

normal screen composable uh this has

play06:44

nothing to do with mvi or MVM it's just

play06:46

something I would always do for compos

play06:47

screens but if we now take a look here

play06:49

at this screen you can see um this would

play06:51

just be maybe a post details screen in

play06:53

the domain of our social network app

play06:56

here we get some post details which are

play06:57

null because they need to be loaded we

play06:59

have a Boolean whether we're currently

play07:00

loading these we have a Boolean whether

play07:02

the post is liked or so and then we also

play07:04

propagate up these lambdas so when the

play07:06

user does something on that screen and

play07:08

in the UI we will then simply interpret

play07:10

the state so what this really means for

play07:12

the UI we check okay if it's loading

play07:14

then we definitely want to show a

play07:15

loading indicator and if not we want to

play07:17

display some kind of pose details and in

play07:20

our view model this will look like this

play07:22

so we have an mvvm view model we have

play07:24

all those different states that have an

play07:26

impact on our UI they could be State

play07:28

flow they could be comp poos state that

play07:30

is really independent of this pattern

play07:31

here and the view model then contains

play07:33

the logic how and when the state should

play07:35

change so here initially we load the

play07:37

post maybe from our API or so when we

play07:39

want to toggle the like we will just

play07:41

change the post detail State here with

play07:44

the like being toggled and when we want

play07:46

to load a post we would first of all

play07:48

update the loading State we load it from

play07:50

maybe a repository a use case or so and

play07:52

then again update is loading to fold

play07:54

again so the view model decides how

play07:56

these states change so this is how mvvm

play07:58

is structured let let's now take a look

play08:00

at mvi so this would be an example for

play08:02

an mvi screen so you can see the first

play08:04

part is already very similar we receive

play08:05

a nav controller reference and a view

play08:07

model but then the list of arguments for

play08:08

the screen always looks a bit

play08:10

differently so here we pass one single

play08:12

state down to our screen composable and

play08:15

we receive one so-called on action or

play08:17

onevent Lambda and that is already the

play08:19

core difference between mvvm and mvi

play08:22

with mvi on the one hand we put all of

play08:24

our screen State into one single state

play08:27

rapper class into UI State class which

play08:29

looks like this for example so in the

play08:31

end we really just expose a single State

play08:33

field to the UI including all those

play08:35

single fields that could have an impact

play08:37

on how the UI looks like and then we

play08:39

just treat this state class as a single

play08:41

source of Truth kind of for that state

play08:43

which should only contain immutable

play08:46

properties that can't be changed and if

play08:48

our state changes then the goal with mvi

play08:51

is to just replace the whole state with

play08:53

a new instance and the changed Fields so

play08:55

if we want to update is loading from

play08:57

false to true we would create a new

play08:58

instance of of the state class just that

play09:01

we set is loading to true in that new

play09:02

instance and leave all the the other

play09:04

fields unchanged so that's one

play09:05

difference about mvi the other

play09:07

difference is this onaction Lambda and

play09:09

this actually implements the intent part

play09:12

about mvi so mvi model view intent the

play09:15

intent part is different compared to MVM

play09:18

it has nothing to do with intents of

play09:20

Android so the Android concept but

play09:22

rather that we want to bundle the

play09:23

specific intention a user could have on

play09:26

a certain screen so in the end every

play09:28

single user interact that could happen

play09:30

on a specific screen will be packaged

play09:32

into such a action class like in this

play09:35

case to toggle alike or to go back and

play09:37

on cutland that's typically implemented

play09:39

with a sealed interface where we can

play09:41

then check in the view model which

play09:43

intent or which action the user actually

play09:45

sent from the UI to the view model and

play09:47

if we then take a look in the view model

play09:49

on the first glance it looks very

play09:51

similar but the main differences are now

play09:53

that we have an mvi view model we only

play09:56

have a single State field which is

play09:58

implemented by our UI State class I've

play10:00

showed you previously so compared to

play10:02

mvvm just to bring that up again here we

play10:04

have every single field as an individual

play10:06

State reference here in MBI we just have

play10:09

a single state class and in order to

play10:11

process these actions these intents that

play10:13

are coming from the UI The View model

play10:14

needs to expose such an onaction

play10:16

function or on event function which then

play10:19

takes the actual intent and checks in

play10:21

when expression what should actually

play10:23

happen for which specific type of action

play10:25

for example when we tole the like it

play10:27

would call the private function toggle

play10:29

like which would again change the local

play10:32

state in this case with state. copy

play10:34

which just creates a new instance of the

play10:36

state and allows us to change just one

play10:38

field or multiple fields of that state

play10:40

in this case the post details value so

play10:42

those are already the differences and

play10:43

you can see that the differences between

play10:45

mvvm and mvi aren't actually too big

play10:47

it's really just about this seal

play10:49

interface and putting all states

play10:51

together in one UI State class but the

play10:53

rest is usually implemented in exactly

play10:55

the same way on Android one thing we

play10:57

need to be a bit careful with with MV is

play11:00

if we have such actions that aren't

play11:03

actually processed by The View model

play11:04

like going back because that requires

play11:06

the nav controller which we usually

play11:07

don't have in the view model so in MV we

play11:10

would actually need to go to our MV MV

play11:11

screen route here and here in this

play11:14

onaction Lambda where where we just

play11:15

forward all actions to the view model by

play11:17

default we would need to intercept these

play11:20

actions and first of all check if the

play11:23

action needs to be handled by the UI

play11:24

itself so when that action is go back

play11:29

then we want to use our nav controller

play11:30

to maybe navigate up otherwise we ignore

play11:33

that here in the UI layer but then we

play11:34

still forward all actions to the view

play11:36

model that is actually something we

play11:38

would need to do here but only if such

play11:40

actions need to be handled in the Y

play11:43

directly but in a lot of cases you also

play11:44

don't have that and you could simply

play11:46

replace this with what I had before that

play11:48

you just say VI model double colon on

play11:50

action so what is now correct what

play11:52

should you use for your Android apps

play11:55

well I don't want to tell you use this

play11:57

or use that in the end both these are

play11:59

very viable and very popular patterns

play12:02

but my goal and my intention here is

play12:04

just that you understand the differences

play12:06

you try them both out and then decide

play12:08

for yourself what you enjoy more what

play12:10

might fit better to your team because in

play12:12

the end it doesn't help you if you stick

play12:14

to a pattern but only a single part of

play12:16

the team sticks to that and the other

play12:18

the other part just introduces some

play12:19

inconsistencies then there is no real

play12:21

point of introducing a design pattern at

play12:23

all but just to maybe highlight the

play12:24

advantages and disadvantages of each

play12:26

pattern so the critics of MV say that

play12:28

having such an intent layer such an MV

play12:32

action seal interface in this case is

play12:35

just an unnecessary extra layer because

play12:37

you could also just expose callbacks in

play12:39

your screen and call The View models

play12:41

functions directly which is pretty much

play12:43

what mvvm does the critics often say

play12:45

that if you have a large screen you will

play12:47

have a very large when expression here

play12:49

checking for the particular action and

play12:51

to some degree that's true obviously

play12:53

this action sealed interface is some

play12:55

kind of an extra class an extra layer

play12:57

but on the other hand it makes the

play12:59

screen composable much lighter and much

play13:01

easier to read in my opinion since for

play13:03

every single screen in your app you only

play13:05

need two parameters which keeps them

play13:07

pretty light also about the critic

play13:08

regarding the when expression I

play13:11

personally never really understood those

play13:13

people why uh potentially big when

play13:15

expression is an issue because you can

play13:17

still work with single private functions

play13:19

and it's very easy to spot what happens

play13:21

in which specific scenario and if you

play13:23

wouldn't have this single function and

play13:25

all those other functions would be

play13:26

public for a very big screen then what

play13:28

would happen for your compose UI is that

play13:31

the list of parameters here would grow

play13:33

by quite a lot because every single

play13:35

function from The View model would need

play13:37

to be a separate Lambda every single

play13:38

state would be would need to be a

play13:40

separate uh field here and of course you

play13:42

can argue you can um combine multiple

play13:45

related States into a data class maybe

play13:47

you can argue that you could potentially

play13:50

also combine such multiple callbacks

play13:52

into a data class but then you again

play13:53

have that extra code which these critics

play13:55

complain about for mvi so does it really

play13:58

make a difference in that case another

play14:00

common criticism of MV is that if we use

play14:02

mvvm and we have all those States as

play14:05

separate Fields it's much easier to

play14:07

combine them let's say they were state

play14:09

flows and we want to combine multiple of

play14:12

these State flows then that would be

play14:13

much easier with single States than if

play14:15

we would have one single state class so

play14:18

one common example might be that you

play14:19

have maybe some some kind of email field

play14:22

here or so we have a private Val email

play14:25

which is a mutable State

play14:26

flow empty string by default and we have

play14:30

aoan is email valid which you could now

play14:34

Implement with reactivity since every

play14:36

time our email changes we want to map

play14:40

that for example to I don't know some

play14:43

kind of valid dator is valid email with

play14:47

the changed email and we then call State

play14:50

in

play14:51

and convert that to some kind of state

play14:54

flow with a typical way here while

play14:55

subscribed and an initial value of false

play14:58

so the critics of VI often say that if

play15:00

you have such single Fields you can

play15:01

implement this reactivity much better

play15:03

you can better combine different states

play15:05

but that's also not really true because

play15:07

if we just have one single um one single

play15:09

compost State here in our MV view model

play15:13

then we can also easily convert that to

play15:14

State flow so we have a function for

play15:16

that where we can let's say um we also

play15:18

have these fields here so Val email

play15:21

empty string by default and we have an

play15:23

is email valid Boolean which should

play15:25

update in real time when we change the

play15:27

email actually Boolean and we then in

play15:29

the view model and we want to react to

play15:31

changes of our email field then we can

play15:33

do that with a snapshot flow so we could

play15:35

just go in here we could have a snapshot

play15:37

flow which will trigger whenever the

play15:39

compos stes in here actually change so

play15:41

whenever our email changes we can also

play15:43

map that flow now to our validator that

play15:47

is valid email with the changed email

play15:50

and then state that in or just update

play15:54

our actual State here with State state.

play15:57

copy is valid email is equal to the new

play16:00

value and we launch that in view model

play16:02

scope that would be the equivalent code

play16:04

here with mvi so just to show you you

play16:06

can also react to changes of specific

play16:08

singal Fields when using such a single

play16:11

state class and all in all my own

play16:13

opinion is that mvi is just a bit more

play16:16

readable because we can just take a look

play16:18

at the state class and in just five

play16:20

lines of code we can completely

play16:22

understand all of those values that

play16:24

could change on a single screen while

play16:26

with mvvm we will very often have a long

play16:28

list of States here first of all if

play16:30

we're using State flow then we will

play16:31

actually have two Fields per single

play16:33

state flow because we always have one a

play16:35

public State flow and then one immutable

play16:38

one where we would have an email is

play16:40

equal to email as state flow and if our

play16:42

screen state contains 30 States then you

play16:45

will have 30 such pieces of code while

play16:48

with MV you can understand that at

play16:50

almost a single glance for a big screen

play16:53

one thing you have to be in fact a bit

play16:54

careful about mvi is that if you have a

play16:56

single state class and you're using X L

play16:59

and then collect that single state in

play17:01

just a normal flow collector then that

play17:03

will trigger for every single change of

play17:05

your state so the whole flow collector

play17:07

will trigger even if you just update the

play17:09

single is loading Boolean which is a

play17:11

performance disadvantage compared to

play17:13

mvvm where you can have multiple such

play17:15

flow collectors for every single field

play17:17

on the other hand for Jetpack compost

play17:18

projects it's not such a big deal

play17:20

anymore because compost is smart enough

play17:22

to detect which Fields actually changed

play17:25

when there is a new instance of MBI

play17:26

State being passed sometimes it does has

play17:28

its issues especially if you use

play17:31

unstable Fields here in such a state

play17:33

class like a normal list where compost

play17:35

can tell for sure if that not changed or

play17:37

not but those are really just a few

play17:38

situations and in this case I'm a friend

play17:41

of not dealing with this premature

play17:43

optimization so not trying to optimize

play17:45

the performance before it becomes even

play17:46

an issue and on the other hand

play17:48

preferring the better readability in

play17:49

your code so that's why I overall tend

play17:52

to stick to MV in my projects but that

play17:54

doesn't mean MVM is bad that doesn't

play17:55

mean MV is the best one don't become

play17:57

religious about such AR architectural

play17:59

design patterns try them out see what's

play18:01

good for you and then use that and you

play18:03

will have a good project structure with

play18:05

either of these patterns so let me know

play18:07

down below what kind of pattern you

play18:09

actually stick to and if you learned

play18:10

something here that you didn't know

play18:11

before and other than that thanks so

play18:13

much for watching this video again Link

play18:15

in this video description regarding the

play18:16

live Workshop in one and a half weeks

play18:18

and other than that have an amazing rest

play18:20

of your week see you back in the next

play18:21

video bye-bye

Rate This

5.0 / 5 (0 votes)

Etiquetas Relacionadas
MVVMMVIAndroidархитектурные шаблоныразработкашаблон проектированиямоделированиеобучениепрактикаWorkshopсоветы
¿Necesitas un resumen en inglés?