-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Добавление событий жизненного цикла для AndroidMVi #24
Conversation
…android' into add_lifecycle_event_for_default_android
…android' into add_lifecycle_event_for_default_android
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
спасибо за такое активное участие в развитии либы, очень полезно 🔥
mvi-core/src/main/kotlin/ru/surfstudio/mvi/core/event/LifecycleMviEvent.kt
Outdated
Show resolved
Hide resolved
mvi-core/src/main/kotlin/ru/surfstudio/mvi/lifecycle/LifecycleBinds.kt
Outdated
Show resolved
Hide resolved
mvi-core/src/main/kotlin/ru/surfstudio/mvi/flow/LifecycleMiddleware.kt
Outdated
Show resolved
Hide resolved
/** | ||
* Sends lifecycle events to the shared event bus | ||
*/ | ||
fun <E : Event> MviView<E>.bindsLifecycleEvent() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно в MviView
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут, насколько это возможно для меня ¯_(ツ)_/¯ , осознаное решение. Хотелось бы сделать код наименее связным. Так, я старался следовать принципу единой ответственности. MviView создает правила, которые должны соблюдать наша вьюха, чтобы реализовать MVI-архитектуру. А вот поддержку обработки событий жизненного цикла я хотел вынести в отдельное расширение. Так наш код будет мене связным и мы можем при необходимости изменить/доработать реализацию
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Но если ты считаешь, что лучше в MviView вынести, то я, конечно, так и сделаю
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
мне кажется, в этом случае можно сразу в MviView, тк она уже является LifecycleOwner, то есть мы не особо разделили ответственность в итоге, а просто вместо расширения сразу будет функция интерфейса, и кому нужно будут ее использовать (если бы действительно расширяли тем, чего не было в MviView, тогда оправдано было бы)
import ru.surfstudio.mvi.vm.android.MviView | ||
|
||
/** | ||
* Map [Lifecycle.Event] from lifecycleScope to [LifecycleMviEvent] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
судя по реализации, в E, надо добавить where для более точного определения события
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Немного не понял 😕
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
комент про LifecycleMviEvent, но по факту <E : Event>
, потому предлагаю ограничить E с помощью where для соответствия описанию
import java.io.IOException | ||
|
||
class SimpleMiddleware( | ||
private val state: FlowState<SimpleState> | ||
) : DslFlowMiddleware<SimpleEvent> { | ||
) : DslFlowMiddleware<SimpleEvent>, LifecycleMiddleware<SimpleEvent> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
) : DslFlowMiddleware<SimpleEvent>, LifecycleMiddleware<SimpleEvent> { | |
) : LifecycleMiddleware<SimpleEvent> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Написал BaseFlowMiddleware. По сути обычный middleware c полной поддержкой LifecycleEvent
Почему я не реализовал MapperLifecycleEvent в LifecycleMiddleware?
Хотелось бы сделать код менее связным. Так, при необходимости мы можем изменить подход не меняя основные сущности т.к они не оч связаны
mvi-core/src/main/kotlin/ru/surfstudio/mvi/lifecycle/MapperLifecycleEvent.kt
Outdated
Show resolved
Hide resolved
mvi-core/src/main/kotlin/ru/surfstudio/mvi/flow/LifecycleMiddleware.kt
Outdated
Show resolved
Hide resolved
/** | ||
* Map [Lifecycle.Event] from lifecycleScope to [LifecycleMviEvent] | ||
*/ | ||
interface MapperLifecycleEvent<E : Event> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
все круто придумано! предлагаю перенести ответственность в middleware, тк у него весь мапинг. LifecycleMiddleware наследует MapperLifecycleEvent, затем поправить доку LifecycleMiddleware и bindsLifecycleEvent (принцип останется тот же, просто теперь viewModel.middleware кастуем к MapperLifecycleEvent)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне только не нравится, что мы пишем каждый раз lifecycle. мне такое не нравилось для события ЖЦ и навигации в прошлом подходе. Я тогда постараюсь поколдовать с хабом и если будут успехи, то сообщу идея не удалась(
…android' into add_lifecycle_event_for_default_android
mvi-core/src/main/kotlin/ru/surfstudio/mvi/flow/BaseFlowMiddleware.kt
Outdated
Show resolved
Hide resolved
/** | ||
* Sends lifecycle events to the shared event bus | ||
*/ | ||
fun <E : Event> MviView<E>.bindsLifecycleEvent() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
мне кажется, в этом случае можно сразу в MviView, тк она уже является LifecycleOwner, то есть мы не особо разделили ответственность в итоге, а просто вместо расширения сразу будет функция интерфейса, и кому нужно будут ее использовать (если бы действительно расширяли тем, чего не было в MviView, тогда оправдано было бы)
/** | ||
* Map [Lifecycle.Event] from lifecycleScope to [MviLifecycleEvent] | ||
*/ | ||
interface MapperLifecycleEvent<E> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
interface MapperLifecycleEvent<E> { | |
interface MapperLifecycleEvent<E> where E: Event, E: MviLifecycleEvent<E> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
это в идеале, чтобы описание соответствовало содержанию, а так как минимум E: Event
* Middleware, that reacts on android lifecycle. | ||
* | ||
* To receive events, you need to add event that implements [MviLifecycleEvent] | ||
* and for your viewModel implements [MapperLifecycleEvent] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
с появлением BaseFlowMiddleware дока не актуальна
mvi-core/src/main/kotlin/ru/surfstudio/mvi/core/event/MviLifecycleEvent.kt
Outdated
Show resolved
Hide resolved
mvi-core/src/main/kotlin/ru/surfstudio/mvi/flow/LifecycleMiddleware.kt
Outdated
Show resolved
Hide resolved
…ware.kt Co-authored-by: Margarita Volodina <[email protected]>
…eware.kt Co-authored-by: Margarita Volodina <[email protected]>
…ycleEvent.kt Co-authored-by: Margarita Volodina <[email protected]>
import androidx.lifecycle.Lifecycle | ||
|
||
/** Screen lifecycle event */ | ||
interface MviLifecycleEvent<E: Event> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
типизация не нужна?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
мб вернуть наследование от Event?
* Base middleware with support of lifecycle events | ||
* | ||
* To receive events, you need to add event that implements [MviLifecycleEvent] | ||
* and to call the [bindLifecycleEventfecycleEvent] for the entity implementing the MviView interface |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To receive events, you need to add event which implements [MviLifecycleEvent]
and to call [bindsLifecycleEvent] for [MviView] implementation
Как ты помог развить студийку?
Предложил возможность добавить событий ЖЦ для андроида
(компоуз опустим)
UPDATE вынес из MviView код, связанный с привязкой lifecycleEvent. Мне кажется, таким образом можно сделать код более гибким
Есть подводные камни?
Сейчас, для связывание нужно сделать 4 действия
Я глубоко уверен, что последние 2 проблемы отойдут в базовые классы на проде, но вот с первыми двумя сложнее. Тяжело так просто взять и скормить событие, которые не связано с событием экрана(из-за сильной типизации и к вопросу о
лидерах протестаэтого ишью #9)Т.е для компоуза ты ничего не сделал? Не стыдно?
Нет. Я пока глубоко убежден, что подход для него будет отличаться. Думаю если мы планируем сделать такую штуку для компоуза, то пр будет сильно больше(или как минимум его стоит смотреть отдельно)
Мы же уходим от стандартного андроида
Да, но если спросите мое мнение(вдруг🥺👉🏻👈🏻) то я скажу, что выглядит будто для компоуза нужно еще достаточно времени, чтобы доработать mvi-flow + написать достаточно кода и определить проблемы архитектуры(и по возможности устранить) + Еще замотивировать наших разрабах для более плотного изучения компоуза
А вот для варианта без компоуза выглядит так, что еще немного доработать и в прод пускать. Подход почти не изменился, но зато новые проекты могут стартануть без рисков и к ребятам будут более низкие требовании, на случай если они еще плохо знакомы с технологией. Таким образом, переход будет постепенный. Оставим привычных подход, но улучшим его и сделаем более современным(Плюс если будем использовать ComposeView вместо виджетов, то таким образом и композировать будем постепенно)
Уже второй пр делаешь без прямых указаний и отвлекаешь от основной работы на писанину многочисленных комментариев. Записывай подобные вещи в ишью и потом на тебя или на кого-то другого назначат
не удержался 👈🏻😨👉🏻
А если наша либа станет очень популярной и кто-то долистает до первых ПРов и увидит как ты их оформляешь?
В будущем более взросло буду оформлять, хотя я итак удерживаюсь и мемы не кидаю в скриншотах...
Есть еще предложения?
Скриншоты(если есть)