<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Semyon Zadoroznyi on Medium]]></title>
        <description><![CDATA[Stories by Semyon Zadoroznyi on Medium]]></description>
        <link>https://medium.com/@szadorozhnyi?source=rss-2a1c1b0a9813------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*15TJiXBA67cxx3xQPuZMPw.jpeg</url>
            <title>Stories by Semyon Zadoroznyi on Medium</title>
            <link>https://medium.com/@szadorozhnyi?source=rss-2a1c1b0a9813------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:11:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@szadorozhnyi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Алгоритмы — самый провальный этап собеседований (RU/EN almost)]]></title>
            <link>https://szadorozhnyi.medium.com/%D0%B0%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%D1%8B-%D1%81%D0%B0%D0%BC%D1%8B%D0%B9-%D0%BF%D1%80%D0%BE%D0%B2%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9-%D1%8D%D1%82%D0%B0%D0%BF-%D1%81%D0%BE%D0%B1%D0%B5%D1%81%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B9-ru-en-almost-b01bb20c0e57?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/b01bb20c0e57</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[devgym]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 14:36:20 GMT</pubDate>
            <atom:updated>2024-08-02T14:36:20.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Алгоритмы — самый провальный этап собеседований (RU/EN almost)</h3><p>(For my English-speaking audience — this article is just an introduction to a small series of articles, all of which will be in English. In this article, I share my experience going through algorithmic sessions in different companies and the problems I see in the algorithms. If you’re interested, feel free to use AI for translation, and subscribe to stay updated on new articles!)</p><p>Уже много лет IT компании проводят алгоритмические собеседования при найме технических специалистов. Подход введенный в FAANG плавно перетек в большинство крупных компаний. Яндекс, Авито, Т-Банк и многие другие хотят проверить алгоритмические знания кандидатов. Но на практике такое собеседование оказывается бесполезным созвоном на 45 минут, который ничего не говорит о кандидате.</p><p>В интернете можно найти тысячи статей о том как решать алгоритмы. Куча теоретических видео про оценку скорости и затраты на память для разных структур данных. Еще больше ресурсов про то, как алгоритмы делают вас сильнее, круче и привлекательнее для работодателя.</p><p>Но очень мало можно встретить критики и конкретного разбора проблем алгоритмических собеседований и их внедрения в воронку найма. Эта статья будет первой в цикле “в чем проблема алгоритмов”.</p><p>Кто-то может сказать: “О, человека не приняли в компанию из-за алгоритмов и он решил обидеться и сказать всем, что алгоритмы бесполезны”. Отчасти это так и было, но я решил не останавливаться на своем чувстве несправедливости и пошел дальше: адаптировал алгоритмы в компании, прошел все этапы в Google и даже решал алгоритмы на протяжении года.</p><p>Все это помогло мне понять, что многие двигаются не туда, когда решают спрашивать деревья и графы на своих интервью.</p><p>Но все это отдельными статьями, ссылки на которые я приложу сюда позже.</p><p>Сейчас я просто хочу рассказать свою историю.</p><h3>Собеседование, которое меня обидело</h3><p>Моя карьера началась в 2015 году. Меня взяли Java джуном в небольшую аутсорс-компанию, потому что я знал немного базы по Java, мог адекватно задавать вопросы и, наверное, не сильно бесил своего начальника.</p><p>Проработав над не очень интересными задачами около года, я решил, что пора дерзать — я должен стать “матерым” разработчиком и ходить под знаменем самого популярного IT-бренда России.</p><p>В то время на российском рынке «царем» IT считался «Яндекс». Попасть в компанию было сложно: вас ожидало нескольких этапов, первым из которых было решение алгоритмических задач.</p><p>Про алгоритмическую секцию мне рассказали на созвоне с HR и убедили, что это классный формат, который явно покажет мои знания. Я про такой фильтр услышал впервые и моментально запаниковал. Как джуну мне были известны базовые структуры данных, но я понятия не имел, как с их помощью решать задачи.</p><p>Мы договорились, что встретимся на собеседовании через 10 дней, и я начал подготовку. Воспользовавшись советом HR, я пошел на Leetcode — самую популярную площадку для тренировки алгоритмов и решал все задачи подряд.</p><p>Сейчас уже не помню, насколько я был неуспешен в своих первых попытках, но точно помню, что у меня уходило очень много времени на то, чтобы понять проблему. Что уж говорить — легкие задачи я решал час-полтора.</p><p>На второй день было понятно, что мне не хватит времени на подготовку. Мало того, впереди меня ждали еще собеседования по андройд, систем дизайну и проектированию на Java.</p><p>Внимательные читатели уже поняли, что это то самое собеседование, которое я провалил. Но давайте я расскажу детали позора.</p><p>Настал день собеседования, меня посадили в кабинет-переговорку, поставили передо мной ноутбук и связали меня с моим интервьюером. Я удивился, что не будет личного присутствия, но удаленный формат общения меня немного расслабил.</p><p>Мне скопипастили задачу в онлайн whiteboard, по сути своей задача была на работу с массивами, и это единственная тема которую я успел разобрать.</p><p>Стресс нарастал и я взял мимолетные две минуты на то чтобы прочитать и понять задачу. Проговорил ее несколько раз вслух. Получил пример входных и выходных данных, но так и не понял как ее решить. Я пытался задавать вопросы, получал подсказки и даже придумал какую-то эфемерную последовательность действий.</p><p>На это ушло слишком много времени. Мой интервьюер со словами: “Решай, у тебя есть все что нужно” пропал с экрана монитора за дверь московского опенспейса. Поставил он на мне крест, подумал что я все понял, или просто ушел за водой, я не знаю.</p><p>Когда он вернулся на нашем общем экране был корявый, точно забагованный алгоритм, а на моем лице — апатия.</p><p>Со мной попрощались и я стал ждать следующего “судью”.</p><p>Все остальные этапы прошли сносно, но мысль “я провалился” оставалась у меня с конца того звонка до вежливого отказа от HR через неделю.</p><p>С тех пор я пытался не связывался с алгоритмами.</p><h3>Ты должен был бороться со злом, а не примкнуть к нему</h3><p>Прошло три года. За это время я успел поработать над большими проектами в B2B и B2C, из бэкенда мигрировал в андроид-разработку, делал крутой видеоплеер, а затем ушел в маленькую криптокомпанию.</p><p>На бумаге я был миддл-инженером, но по факту мне приходилось принимать высокоуровневые решения и отвечать за разные аспекты проекта. С того провального собеседования я не написал ни строчки алгоритмов, но я бы не сказал, что потерял какой-то навык, ведь я его и не приобретал.</p><p>Тогда на подкорке сознания у меня звучала сладкая, но страшная мысль — попробовать свои силы в собеседованиях в иностранные компании. Комфортные условия жизни отодвигали эту идею, но в один день я узнал, что мой бывший коллега и ментор попал в Bolt. Видимо, я понравился ему на этапе обучения, и одним прекрасным утром он постучался ко мне в личку:</p><blockquote><em>йоу как ты смотришь на вариант с тем, чтобы я тебя порекомендовал на этой неделе? Как раз на след. неделю тебе смогут запланировать тех. собес )</em></blockquote><p>Я человек простой — плыть по течению это мое, но вот такие “пинки” я никогда не игнорировал.</p><p>Собеседование должно было состояться через неделю.</p><p>На этот раз не было гнетущего взгляда собеседующего, даже временного, так как всё делалось в автоматизированном сервисе. Все мои действия записывались в реальном времени. Сначала я переживал, что некому задать вопрос, но это было не нужно. Задача была на массивы, которые я зарешал и зазубрил наизусть: «Переверните все слова в массиве без знаков пунктуации».</p><p>Главное отличие от прошлой подготовки к собеседованию — я правильно решил задачу на собеседовании и получил хорошую инъекцию эндорфина от своего успеха.</p><p>Какой самый неправильный вывод я сделал из этой ситуации? Правильно — нужно внедрять подобное у себя, потому что это быстро и приносит удовольствие. А если ты разработчик и не получаешь хороших эмоций от своих решений, то ты плохой специалист.</p><p>Сама наивность.</p><p>Я был единственным андройд разработчиком на проекте и в это же время мы искали мне младшего спеца в помощь.</p><p>Я не задумываясь взял свою любимую задачу “Найти k максимальный элемент в списке”(<a href="https://leetcode.com/problems/kth-largest-element-in-an-array/">https://leetcode.com/problems/kth-largest-element-in-an-array/</a>) и взял ее как практическую задачу вдобавок к теории, которую я спрашивал.</p><p>Конечно я предусмотрел, что задача сложная в той постановке, которая озвучена на сайте, поэтому я не запрещал сортировку. Но спрашивал дополнительно, если мы справлялись быстро.</p><p>После одного из таких собеседований, один из кандидатов, которого я мучал этой задачей и я вышли из переговорки и состоялся следующий диалог:</p><p>Он: А зачем ты меня это спрашивал, как тебе это помогло<br>Я: Я смотрел на то как ты пишешь код и задаешь вопросы <br>Он: А не легче было написать какой-нибудь код, который что-то делает полезное в рамках приложения <br>Я: У моей задачи есть решение, мне важно чтобы ты его нашел</p><p>Он молча попрощался и пошел по своим делам, а я понял, что мне не важно было, чтобы он дошел до решения. Мне было важно, чтобы мы нашли общий язык и я понял, что я могу с ним работать. Я навсегда выкинул алгоритмы из уравнения, а его принял на работу.</p><h3>Момент, когда я понял, что алгоритмы адаптируются неправильно</h3><p>Мы возвращаемся в (почти) настоящее время, в 2022 году я взял выше и собеседовался в Google</p><p>На этот раз я был настроен на успех, для подготовки я взял два месяца. При этом у меня не было работы, поэтому алгоритмами я занимался по восемь часов в день. За два месяца я решил 300+ задач, с упором на средние и сложные — других Google не спросит.</p><p>На тот момент алгоритмы плотно уже въелись в IT-культуру бигтеха СНГ, так что у меня была возможность попрактиковаться. Я подавался на собеседования везде, где были алгоритмы, и без особых проблем их проходил. Мне давали хорошие отзывы и офферы, но я чувствовал себя мошенником — я не считал себя крутым специалистом, я просто уделил кучу времени алгоритмам.</p><p>Однако мой фокус был именно на собеседовании в Google. Я стремился к точке отсчета, чтобы понять, как они проводят собеседования.</p><p>То что я увидел в Google — совсем другая история, на нее я напишу отдельную статью, но если кратко, то именно тут я увидел, что алгоритмы это ширма за которой прячется множество других критериев по которому вас оценивают. Вы не решаете алгоритмическую задачу, вы с вашим потенциальным коллегой решаете рабочую проблему, тут не важен язык программирования и даже не всегда важен рабочий код.</p><p>Ваш способ мышления, то, как вы общаетесь и обсуждаете проблемы, — вот что оценивают на собеседовании. Да, задачу все еще нужно написать полностью, но это не самое важное, это просто один из паззлов большой мозайки.</p><p>На этом моменте стоит сказать что мое мнение сугубо субъективное, я пытаюсь собрать больше точек зрения, поэтому недавно на подкасте я поговорил с моим соведущим Игорем Климовым про его мнение на этот этап собеседований</p><p><a href="https://devgym.mave.digital/ep-16">Devgym.Podcast</a></p><p>Игорь работал в VK и тоже в одно время со мной собеседовался в FAANG, мы вместе готовились к собеседованиям. Что уж там, мы даже приходили на канал Mobile Developer, чтобы побатлиться и порешать задачи перед большой публикой (Игорь победил, я считаю)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsUyHETtIh_A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsUyHETtIh_A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsUyHETtIh_A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a505380cdfd46fcef02f97dd0555435/href">https://medium.com/media/4a505380cdfd46fcef02f97dd0555435/href</a></iframe><p>Несмотря на то что мы уже давно не практикуем алгоритмические задачи у Игоря остается вера в то что это эффективный фильтр на собеседованиях, хотя он согласен что знания эти в работе редко применимы и нет гарантии объективной оценки.</p><h3>А вот пример, почему алгоритмы полезны…</h3><p>Ровно такой комментарий я ожидаю от вас под этой статьей, поэтому пишите, не стесняйтесь. Даже если я найду аргументы на ваше мнение, я постараюсь дать самый конструктивный ответ и привести пример, как это можно сделать по другому.</p><p>На мой взгляд, алгоритмическая секция это рудимент того подхода, который разрабатывали FAANG компаниях под свои нужды, почти все компании перенимают его из-за его простоты и популярности.</p><p>Лень сделала много, вся индустрия айти делается на столпах оптимизаций и капитализма. Та же лень внесла алгоритмы в современные хайринг воронки — тут тебе и 3000+ готовых задач разной сложности и отсутствие инструментов для собеседования — открыл блокнот и решай проблемы, а мы уже скажем правильно ты это сделал или нет.</p><p>Самое смешное, что если вы дадите своему коллеге решить алгоритмическую задачу забавы ради, то он ее не решит — это не тот скилл, который часто используется в работе.</p><p>Если у вас в собеседованиях есть алгоритмы, спросите себя: “Если кандидат уже успешно прошел все остальные этапы, давать ли ему задачу с Leetcode” А даже если решили дать, представьте что он ее не решил. <strong>Стал ли он после этого плохим специалистом?</strong></p><h3>Эндшпиль</h3><p>Круто что вы дочитали до этого момента, вот вам за это картинка (там кстати еще два полных месяца в 2022 году, это момент подготовки в Google)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M80fwVgz-hC3Jyd2BEvYKQ.png" /><figcaption>Год страданий</figcaption></figure><p>На ней мой эксперимент: “А буду ли я крутым специалистом, если буду продолжать решать алгоритмы каждый день в течении года”.</p><p>Этот эксперимент я делал ради вас, прошу не повторять, все трюки уже выполнены и не очень впечатляют.</p><p><strong>Какие выводы за этот прекрасный год я сделал:</strong></p><ol><li>на дворе 2024 год, я все забыл</li><li>это нужно только для собеседований</li><li>я не стал круче, наоборот, иногда я пытаюсь “сделать алгоритм” там, где это не нужно</li><li>компании плохо адаптируют алгоритмическую секцию</li></ol><p>Что в алгоритмах дает вам понять, что человек классный специалист? Что даст вам понять, что он готов расти? Как алгоритмы позволяют брать на себя ответственность? Зачем и как правильно внедрять алгоритмы?</p><p>Эти вопросы мы частично разобрали на подкасте</p><p><a href="https://devgym.mave.digital/ep-16">Devgym.Podcast</a></p><p>и на оставшиеся я подробно отвечу в следующих статьях, поэтому подписывайтесь, чтобы не пропустить!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b01bb20c0e57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Custom Design System Using Jetpack Compose]]></title>
            <link>https://medium.com/better-programming/custom-design-system-using-jetpack-compose-17a59b1ae38d?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/17a59b1ae38d</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 14:32:00 GMT</pubDate>
            <atom:updated>2023-09-24T08:58:45.840Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s replace Android’s material package with our own implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex6wMZK46zZmPBf2J_qKJA.png" /></figure><p>In this article you will find out:</p><ul><li>What a Design system is</li><li>What ways to implement your Design system there are in Jetpack Compose</li><li>How to implement a Design system based on the foundation package and completely exclude the Material library from your project.</li></ul><h3>Design system in a nutshell</h3><p>UI design system is a collection of standards for designing and coding, which includes a set of components created according to certain rules which create a single UI concept of the product. A design system can be seen as instruction and a set of components which can be used to build the final version of the design.</p><p>Quite often a design system is divided into a few layers:</p><ul><li>Atomic layer: it is a set of atomic elements, for example, a set of colors, typography rules, component corner shapes, elevation, and padding.</li><li>Molecular layer: it is a basic set of UI widgets with minimal functionality using molecules for styling. An example of molecules can be Text, Icon, Avatar, Border, Separator components.</li><li>Organism layer: it is a component made of one or several molecular components.</li><li>Screens layer: it is a set of components from organisms and molecules.</li></ul><p>A design system solves the problems of:</p><ul><li>management (design and development team finds a common language)</li><li>“the only source of truth” in the context of design</li><li>changeability of atomic layer (by changing the values of colors, typography and corner shapes, you can get a modified UI style)</li><li>extensibility (large components are built on top of smaller/pre-build ones)</li></ul><p>At the moment, there are quite a few implementations of design systems of big companies. The two most known are:</p><ul><li><a href="https://material.io/">Material Design from Google</a></li><li><a href="https://developer.apple.com/design/human-interface-guidelines/guidelines/overview/">Human Design from Apple</a></li></ul><p>These design systems are used not only within companies but are also recommended for implementation in applications which are written for both Android and iOS devices. The companies use the fact that a user is familiar with such a design format to encourage their use, and their approaches to design these design systems are scientifically and experimentally substantiated.</p><p>Examples of other design systems:</p><p><a href="https://uxplanet.org/top-12-design-systems-to-steal-from-and-up-your-design-game-520235d7de76">Top 12 Design Systems to Steal from and Up Your Design Game</a></p><p>For the purpose of this article, I chose a rather raw yet well-structured design system from the Figma Community portal. You can follow the <a href="https://www.figma.com/file/z2BtuZqLwoXw7gnXu8AZAL/Design-System-Foundation-(Community)?node-id=108%3A95">link</a> to watch it and simultaneously follow its implementation in the <a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem">project</a>.</p><p>After seeing the cover of this design system, I decided to name it SpaceTheme.</p><h3>Design system in Jetpack Compose</h3><p>To begin with, it is worth mentioning that <em>Google </em>has already made sure that its design system is implemented in the code. So developers are able to take ready-to-use components and configure them at their discretion.</p><p>androidx.compose.material package is responsible for this in the code — in which you can find many ready-to-use components. Their description and specifications can be found in the official <a href="https://material.io/components/">Material Design documentation.</a></p><p>Despite of the presence of ready-to-use components, Google provides space for customization and implementation of your version of a design system in the project. Here is what Google says about it:</p><blockquote><em>There are several approaches you might take:<br>- </em><a href="https://developer.android.com/jetpack/compose/themes/custom#extending-material">Extending </a><a href="https://developer.android.com/jetpack/compose/themes/custom#extending-material">MaterialTheme</a> with additional theming values<br>- <a href="https://developer.android.com/jetpack/compose/themes/custom#replacing-systems">Replacing one or more Material systems</a> — Colors, Typography, or Shapes — with custom implementations, while maintaining the others<br>- <a href="https://developer.android.com/jetpack/compose/themes/custom#implementing-fully-custom">Implementing a fully-custom design system</a> to replace MaterialTheme</blockquote><p>Based on my experience of working with Jetpack Compose and opinions of some of my acquaintances, who write projects on it, the first two approaches are the most used ones by developers.</p><p>In a new article from <em>Tinder</em>, they shared their progress in Compose integration and said that their theme is also built on top of Material Design, and a few components are written on the basis of the foundation package. You can find more information in their article.</p><p><a href="https://medium.com/tinder/sparking-jetpack-compose-at-tinder-8f15d77eb4da">Sparking Jetpack Compose at Tinder</a></p><p>So, what does ‘<em>based on the foundation package</em>’ mean?</p><p>Jetpack Compose is architecturally built in layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZA6tLcT8bsPJ3RnfhJ1_fA.png" /></figure><p>At the top of the graph, there is Material package that implements Material Design. Jetpack Compose developers imply that the Material package is fully optional and can be replaced with your custom design system.</p><p>The final result of our work will contain the following layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPnGSC8Tb19Q79F2BmblHg.png" /></figure><p>And this is what we are going to do: create a new Compose project and make the first commit by getting rid of the material package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mH631G6ogCyhoIwLVSTmTg.png" /></figure><h3>Implementation of a design system theme</h3><p>Let’s begin with simple things. We need our own alternative of MaterialTheme in which we will lay out our screens. Let’s call it SpaceTheme, and here is what its implementation will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98b15c65f6a0ee36e2dc9aebf26d147a/href">https://medium.com/media/98b15c65f6a0ee36e2dc9aebf26d147a/href</a></iframe><p>It is implied that in the design system we have color typography and corner smoothing as atoms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJD9A2DKEQk9jwHl5y6Egw.png" /><figcaption><a href="https://www.figma.com/file/ExIQQj62VM2QzGe7QDVaZE/Design-System-Foundation-(Community)-(Copy)?type=design&amp;node-id=109%3A287&amp;mode=design&amp;t=9WQjKh9hkXAfZPNi-1">https://www.figma.com/file/z2BtuZqLwoXw7gnXu8AZAL/Design-System-Foundation-(Community)?node-id=2%3A121</a></figcaption></figure><p>Despite the fact that corner values are not described anywhere, you can see it clearly in the implementation of components in the design system. It is a minor mistake of the design system’s author but not a critical one.</p><p>Let’s start with SpaceShapes. We are going to have three types of corners in total - 8, 16 and 45 dp. There is also LocalShapes object for static composition, so that the corners can be used in the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca90ca9ff7cffab3b5369a74a8b242c/href">https://medium.com/media/4ca90ca9ff7cffab3b5369a74a8b242c/href</a></iframe><p>The next step is typography and there are only 9 types and 2 font-weight — regular and bold. <strong>BM Plex Sans</strong> is used as a font. It can be downloaded from <a href="https://fonts.google.com/specimen/IBM+Plex+Sans?query=ibm+ple">Google Fonts</a>. In the constructor, we set default values for our fields and at the end of the file we create a field for the static composition LocalTypography</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbb779515aa406e88af68b98209a6f6f/href">https://medium.com/media/dbb779515aa406e88af68b98209a6f6f/href</a></iframe><p>Colors are the most routine part of writing this design system, since, unlike Material where with 12 primary colors defined, our system has 32 of them! As well as lightSpaceColors/darkSpaceColors for setting default color values for light and dark themes.</p><p>Additionally, we will create a contentColorFor method to determine what color the content should be on a particular background color (mapping of these colors is calculated from the analysis of the design system).</p><p>In the end, we will create compositions for working with LocalColors colors and the content color LocalContentColor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aee8c0e2caa586673cc5e4a2edbf1697/href">https://medium.com/media/aee8c0e2caa586673cc5e4a2edbf1697/href</a></iframe><p>All these classes and full implementation you can find in the project on GitHub in the package <a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/tree/main/app/src/main/java/com/compose/designsystem/ui/theme">com.compose.designsystem.space.theme</a></p><p>After implementing a custom theme, we can proceed to the implementation of our components based on it. Let’s first analyze our abilities after deciding not to use Material Design.</p><h3>What component we lost bypassing Material</h3><p>During the implementation of this design system, after I finished working with atoms, I proceeded to small components straightaway, and this is where I got a big surprise.</p><p>Let’s take a closer look at what the Link component in the design system consists of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*arUbfQAL36h69QpvTQvU9g.png" /><figcaption><a href="https://www.figma.com/file/z2BtuZqLwoXw7gnXu8AZAL/Design-System-Foundation-(Community)?node-id=3%3A253">https://www.figma.com/file/z2BtuZqLwoXw7gnXu8AZAL/Design-System-Foundation-(Community)?node-id=3%3A253</a></figcaption></figure><p>Link is a set of several components. The text is at the top, the link has an icon before or after the text, small Border can be displayed below the text, and the background of the link can change.</p><p>If we were to do it in Compose, like we are used to, we would use Surface for background, Text, Icon and Border for the rest of the components. However, there is a little problem. All these components are part of the material package, so we have to implement them by ourselves.</p><pre>androidx.compose.material.Text(text = &quot;Link&quot;)<br>androidx.compose.material.Divider()<br>androidx.compose.material.Icon(painter = .., contentDescription = null)<br>androidx.compose.material.Surface()</pre><p>It is fine though since the key @Composable functions are still at our disposal, such as Row, Column, Box, Layout, BasicText, Spacer, Image and all sorts of Modifiers</p><h3>Overview of the screens from top to bottom (from organisms to molecules)</h3><p>A small disclaimer: we have already covered everything that was necessary in order to create your own theme. The implementation of the components from the design system will be described below. There can be a lot of variations for this implementation. I focused on specific and not the most complex ones. I will not fully describe all the nuances but highlight interesting points in the implementation of several components.</p><h4><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/first/FirstSpaceScreen.kt">Transaction history screen</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l81NUrAPcxvdWFp0-VMXOA.png" /></figure><p>This one requires such components as Text, Border, Icon, Tabs, Tab, NavBar and NavTab</p><p>Let’s start with the Text component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e7993cbe9995a1c3ab812c9264d057/href">https://medium.com/media/e6e7993cbe9995a1c3ab812c9264d057/href</a></iframe><p>A noteworthy thing here is the sequence of calls to the takeOrElse functions, which are used to determine the color our text will have. We prioritize the color the developer set. If it is Undefined, we take the color from the provided text style. If the color from the text style is also Undefined, then we take the value from the static composition, it is always not Undefined and can be default. In my project it is black.</p><p>LocalContentColor.current also allows us to change the color if, for instance, we have a button and it overrides the color value for its content, such an example can be found below.</p><p>To display text, we take BasicText from the foundation package and pass information to it.</p><p>We will not cover Divider here, it is a complete copy of Divider from the Material package.</p><p>We also won’t use anything extra for Icon. A simple Box and a combination of toolingGraphicsLayer and paint modifiers will be enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e1229ff1247676ce095ff8d1e0f5325/href">https://medium.com/media/5e1229ff1247676ce095ff8d1e0f5325/href</a></iframe><p>The Tabs and NavBar organisms contain Row of smaller components. Below there is an implementation of Tabs. NavBar is made in a similar way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7266efa489050af440a85057563c6a7/href">https://medium.com/media/b7266efa489050af440a85057563c6a7/href</a></iframe><p>In this part the Surface component is worth paying attention to. It is not in the foundation package and, essentially, it is a convenient wrapper over Box that encapsulates the settings for colors, shapes and semantics for the accessibility of the framework. You can also find an example of redefining the content color here. Placed on such a Surface, the Text component will use LocalContentColor.current to set the text color</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e79e0ece3daadbbdcd7720a0370be6d7/href">https://medium.com/media/e79e0ece3daadbbdcd7720a0370be6d7/href</a></iframe><p>Tab and NavTab components a little bit more complicated, you can find their <a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/tree/main/app/src/main/java/com/compose/designsystem/space/atoms">implementation here</a>.</p><p>What is left to do now is to put all components on one screen. The screen itself can be found on <a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/first/FirstSpaceScreen.kt">GitHub.</a></p><h4><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/second/SecondSpaceScreen.kt">Screen with BottomSheet</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgIEiI0nlZn-f-5DWMRsmQ.png" /></figure><p>Here, we add the Button component and the ability to open the BottomSheet on part of the screen</p><p>Let’s start with the button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXm7iN1vxueUi_QKCTJ47w.png" /></figure><p>It can be seen in the design that we have to configure the type of button — the color depends on this. You can add an icon to the button before and after the text, as well as configure the shape of the button.</p><p>I used the slot-based API, in case we want to insert something other than text. Slot-based is about passing one or more @Composable functions so as not to heavily restrict the implementation of the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e6e04f5293ec652181ad3036c4730d/href">https://medium.com/media/d9e6e04f5293ec652181ad3036c4730d/href</a></iframe><p>The button uses SpaceTheme.typography.h4 typography by default and just lays out the components on Row with little padding.</p><p>After that, you can write a simple screen implementation that can show the BottomSheet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a7afa27919708b2eb497086fb3990b7/href">https://medium.com/media/0a7afa27919708b2eb497086fb3990b7/href</a></iframe><p>BottomSheetScreenStack in this example is responsible for the way content of different levels will be drawn on the screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1cb90ccbfdca85f1bc21edf815309c/href">https://medium.com/media/5f1cb90ccbfdca85f1bc21edf815309c/href</a></iframe><p>This is where we create Layout for the component, the content takes up the entire screen and BottomSheet is nailed to the bottom of the screen.</p><h4><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/third/ThirdSpaceScreen.kt">Prompt screen</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5OPKZOS0QfHKeQ5FEgJFw.png" /></figure><p>The greatest challenge here is to show the dialogue to the user. In material, it was handled with AlertDialog. The foundation package provides us with @Composable Dialog which we just need to wrap in our Prompt and define its style and content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fcc58f2e41e443c2c0432c249f53f28/href">https://medium.com/media/8fcc58f2e41e443c2c0432c249f53f28/href</a></iframe><h4><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/forth/ForthSpaceScreen.kt">Checkout screen</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVKHsPVsS0ECkLkEi0FCbg.png" /></figure><p>The Form/Card organism is a noteworthy thing here, which essentially contains content and a confirmation button</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70f033b751564882bcc2ee7f5b6cac0a/href">https://medium.com/media/70f033b751564882bcc2ee7f5b6cac0a/href</a></iframe><p>InputGroup and SelectGroup are small organisms that include a title, a field for entering or selecting an option, and a subtitle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDVhG8Giz6D7PtWO18iLHw.png" /></figure><p>There is nothing interesting in these components, but input field itself is worth paying attention to. The foundation package provides BasicTextField that processes user input and displays it on the screen. For the visual component, the decorationBox field is used</p><pre>decorationBox: @Composable (innerTextField: @Composable () -&gt; Unit) -&gt; Unit =<br>        @Composable { innerTextField -&gt; innerTextField() }</pre><p>It’s a @Composable component that you define yourself and put an innerTextField in it.</p><h4><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem/blob/main/app/src/main/java/com/compose/designsystem/application/fifth/FifthSpaceScreen.kt">Profiles screen</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QrCaDMIbbR254onCnZ2oTg.png" /></figure><p>This screen is based on already existing components, the only added widget is Avatar. Its implementation is easily done with Box and there are no unique approaches. So as not to make it too long, I will not describe its implementation.</p><h3>Conclusion</h3><p>In this article we covered:</p><ul><li>What a design system is and what it is used for</li><li>How design system is implemented in Jetpack Compose and what methods for implementation of your own theme there are</li><li>How to implement your theme without using Material Design in your application</li><li>Examples of component implementations on a custom design system for creating multiple screens</li></ul><p>I’d like to remind you that the entire implementation is publicly available in the project:</p><p><a href="https://github.com/ZadorozhnyiSemen/ComposeDesignSystem">GitHub - ZadorozhnyiSemen/ComposeDesignSystem: Custom design system</a></p><p>My main goal was to try using Jetpack Compose to bypass the material package because in production projects I used to write all the designs on top of material.</p><p>From my personal experience, if you already have a well-developed design system on the project and it doesn’t look like Material Design, it will be better to implement it yourself and just take the code from the material as an example, because now many things in Compose are very specific and tied to the specification of Material design. For instance, if you need to show Snackbar from the top of the screen in Scaffold, then you have to make your own Scaffold implementation.</p><p>When I was writing the test project, I spent most of the time on colors, typography, and some components. After I finished writing the components, laying out the screens was just as easy as with the Material components.</p><p>That’s it for now, if you are interested in MVI for Jetpack Compose, you can read a series of articles on this topic at the links below:</p><p><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">MVI for Compose (Part 1)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17a59b1ae38d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/custom-design-system-using-jetpack-compose-17a59b1ae38d">Build a Custom Design System Using Jetpack Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI for Compose (Part 5)]]></title>
            <link>https://szadorozhnyi.medium.com/mvi-for-compose-part-5-d59980388d61?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/d59980388d61</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 09:41:57 GMT</pubDate>
            <atom:updated>2022-08-26T09:41:57.196Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">Problems and benefits of MVVM</a></li><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-2-63f9734c7d5a">Custom MVI</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">Practical examples, continued implementation</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4-6c0e31bd5a15">Automating/reducing boilerplate</a></li><li><strong>Best practices and conclusions</strong> (you are here)</li></ul><p>In this part I’m going to talk about some rules and recommendations which should be followed in order to avoid non-obvious problems, and draw some conclusions regarding the use of MVI approach If you are here but haven’t read the previous articles, please follow the links above to find them.</p><h3>Exhaustive ‘when’</h3><p>When processing intents using handleIntent and reduce methods, you have to use the construction ‘when’ and avoid using ‘else’ block in order to make compilator process all new intents and signal that intent needs processing if it has just been added. In the case of reduce you just have to return previous screen state if nothing is happening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b9487956e257ecdad169af9083d48f/href">https://medium.com/media/73b9487956e257ecdad169af9083d48f/href</a></iframe><h3>Intent on first load</h3><p>There are cases when it’s necessary to start some intent along with screen start and initialising MVI. In this case two approaches can be used:</p><ol><li>Start LaunchedEffect(Unit) from @Composable</li><li>Use the init method in MVI class</li></ol><p>However, there are cases when LaunchedEffect(Unit) starts several times, for instance, when a configuration has been changed, so it is preferable to use the second method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2dcd5a72bbf40f0b3c9738a2adb912b/href">https://medium.com/media/e2dcd5a72bbf40f0b3c9738a2adb912b/href</a></iframe><h3>Fields in MviProcessor class</h3><p>If you need to add some additional fields to your MVI which contain data, it’s better to stop and refactor the contract. All data should be transferred to screen state and store only there and in intents. In order to prevent human error, Lint rules can be written for large projects which will prohibit creating fields at the class level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a5b51972724955e53c4f7cd3a3a07d/href">https://medium.com/media/e1a5b51972724955e53c4f7cd3a3a07d/href</a></iframe><h3>Use Holders to handle state and intents</h3><p>As Google recommends, when you work with Jetpack Compose it is better to use middleware function which will contain all non-UI rendering-related operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iCqiApUyegGHr5UO7kTtQ.jpeg" /></figure><p>Screen or component should only depend on state and provide callbacks for user interactions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5286396867b8c5cf1566cabb86f8c92d/href">https://medium.com/media/5286396867b8c5cf1566cabb86f8c92d/href</a></iframe><p>An example of a more complex Holder you can see in the <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI/blob/main/app/src/main/java/com/mvi/example/gamelobby/presentation/GameLobbyScreen.kt">project</a>.</p><h3>Split MVI’s for unrelated components</h3><p>Compose allows you to use LocalViewModelStoreOwner.current to inject ViewModel into different screen components. If your screen parts are independent, it doesn’t make sense to handle them in one contract, just break the contract into independent parts and assign a different MVI to each part.</p><p>Full code you can find in the <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI/tree/main/app/src/main/java/com/mvi/example/splitmvi">project</a></p><h3>Navigation</h3><p>Nowhere in the code you will find examples of navigation using this approach. The first reason is that presentational patterns are not supposed to be responsible for it. And another reason is that there is a variety of different methods. When working with the approach described above I used inject of the router into MviProcessor** class constructor. It allowed with certain intents to trigger navigation events and separate them from MVI logic.</p><p>However, there is a caveat: intents come from the user and from the system without any filters, so they might get duplicated (for example, a user double-clicked the Next button). There are two options in this case. Either the button goes into disabled state after the first intent, or navigation events are passed through “debounce”. In the first case, state contract grows a little, in the second one, processing of navigation events becomes more complicated. The choice is up to the reader.</p><h3>Testing</h3><p>Testing is no different from testing MVVM. You create an instance of your MVI, subscribe to viewState updates, and after running intents, validate the UI state</p><h3>Conclusions</h3><p>The approach described in previous articles shows a simple way to implement MVI and examples of its use. It was on a production application and allows you to quickly develop UI and UI logic for screens.</p><p>This approach is a great replacement for the old development of mvp applications with MVI if you use Jetpack Compose, and with proper automation it perfectly replaces old MVP (Model-view-presenter) approaches for designing small screen, it also scales and decomposes well for large projects.</p><p>It does not work with cross-platform and relies on ViewModel, if this is a problem for you, you can use <a href="https://github.com/uber/RIBs">Ribs</a> or <a href="https://github.com/arkivanov/Decompose">Decompose</a>.</p><p>It is not a library, and it is in your power to expand and customise the functionality as you need.</p><p>It doesn’t take a lot of space, just two code files which can be placed in a separate module or on artifactory.</p><p>It is easy to use. A lot of MVI libraries provide more functionality but have a higher entry threshold and complex api.</p><p>That’s all for now, your comments and thoughts are welcome. See you soon!</p><p><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4-6c0e31bd5a15">&lt;- Previous part</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d59980388d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI for Compose (Part 4)]]></title>
            <link>https://szadorozhnyi.medium.com/mvi-for-compose-part-4-6c0e31bd5a15?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0e31bd5a15</guid>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 09:12:28 GMT</pubDate>
            <atom:updated>2022-08-26T09:12:28.331Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">Problems and benefits of MVVM</a></li><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-2-63f9734c7d5a">Custom MVI</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">Practical examples, continued implementation</a></li><li><strong>Automating/reducing boilerplate</strong> (you are here)</li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-5-d59980388d61">Best practices and conclusions</a></li></ul><p>If you believe that you have been brought here by some magic forces or a medium for example, and you haven’t read previous parts, here is what we have already discussed: in the first part you can read about cons of MVVM approach, in the second one you will learn about a simple yet effective implementation of MVI, and the third part shows specific examples of usage.</p><p>In this article, we will try to analyse the problems which are present in MVI itself and in the implementation described earlier.</p><h3>Boilerplate code</h3><p>This is the problem of MVI itself. When developing mvp applications, a lot of team stay away from MVI and try to use frameworks which are easy to implement, even MVVM is not a priority in this case</p><p>It would be logical to assume that the larger screen contract is, the more things have to be described in reducer and side effects processing. And contract itself needs to be described.</p><p>So how can we save time?</p><p>If you have the resources, you can write your own gradle-plugin to generate files when you are planning to create a new screen and mvi for it. In order to do it you going to need only the screen name, the rest is going to be done for you by IDE. It will generate files of the contract, MviProcessor and screen. It will create **State, **Intent, **SingleEvent objects, automatically create subscriptions to viewState and singleEvent in your @Composable. It will initially override all Mvi class functions and, if you want, generate files and code for DI. All you will have to do is to describe how your MVI works.</p><p>Since gradle-plugin is not that fast to write, we made a decision not to waste time and just write a few Live templates to generate code faster.</p><p>Here is an example of contract generation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71d92f218fa12767d4850e0ccdee323e/href">https://medium.com/media/71d92f218fa12767d4850e0ccdee323e/href</a></iframe><p>In the same way you can get Live templates for our MVI classes and screens.</p><h3>Overloaded Mvi class</h3><p>The larger the contact in your MVI, the larger ‘when’ conditions for the methods reduce and handleIntent. In our case handling each intent in a separate function seems to be a convenient solution.</p><p>You can take out the code from handleIntent, but we decided not to do it because:</p><p>a) you need to pass usecases/interactors into separate methods or class</p><p>b) it is necessary to provide public access to the triggerSingleEvent and observeFlow functions, and this guarantees the incorrect use of these methods in future.</p><p>But if we imagine that such an approach can be applied, then this is what everything will look like</p><p>In the example with a timer we had:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d8cb9dbf16d391a6355ac61c18b7af0/href">https://medium.com/media/6d8cb9dbf16d391a6355ac61c18b7af0/href</a></iframe><p>After taking out</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68ffee4058cdfd0e630717479ab4f99f/href">https://medium.com/media/68ffee4058cdfd0e630717479ab4f99f/href</a></iframe><p>handle*** methods moved to a separate file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/498dc85997293525b24afa63397b3c49/href">https://medium.com/media/498dc85997293525b24afa63397b3c49/href</a></iframe><p>On Github you can find an <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI/tree/main/app/src/main/java/com/mvi/example/gamelobby">example</a> with a complex contract which simulates a waiting lobby for a player in an online game.</p><p>Now let’s talk about good practices, see you in the next part.</p><p><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">&lt;- Previous part</a> | <a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-5-d59980388d61">Next part -&gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0e31bd5a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI for Compose (Part 3)]]></title>
            <link>https://szadorozhnyi.medium.com/mvi-for-compose-part-3-99d2e90d76ef?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/99d2e90d76ef</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 09:03:27 GMT</pubDate>
            <atom:updated>2022-08-26T09:03:27.207Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">Problems and benefits of MVVM</a></li><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-2-63f9734c7d5a">Custom MVI</a></li><li><strong>Practical examples, continued implementation</strong> (You are here)</li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4-6c0e31bd5a15">Automating/reducing boilerplate</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-5-d59980388d61">Best practices and conclusions</a></li></ul><p>In this chapter we are going to have a look at 2 simple examples and find out what else is needed for our implementation</p><h3>Example 1: simple data loading</h3><p>Let’s say that after starting the app we see a screen with a button, and after you click on it, a loading indicator appears, and after the loading is over, there is a list.</p><p>What the state of such a screen is going to look like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b10ed8ca6b86295b977ded4de9761788/href">https://medium.com/media/b10ed8ca6b86295b977ded4de9761788/href</a></iframe><p>Everything is quite simple with intents. We have two intents, the first one triggers the loading, the second one comes from the system when friends are loaded</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e057d5dcbf3f8ad0341f39d2804c1e1c/href">https://medium.com/media/e057d5dcbf3f8ad0341f39d2804c1e1c/href</a></iframe><p>As we don’t have single events yet, we’ll leave them empty</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeed6793b66decc7bd99022b9e0bb16f/href">https://medium.com/media/eeed6793b66decc7bd99022b9e0bb16f/href</a></iframe><p>Now in MVI of our screen we implement MVI with our contract</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e714c7e1084426d8398ea3a33615bb5/href">https://medium.com/media/9e714c7e1084426d8398ea3a33615bb5/href</a></iframe><p>The situation with initial state is simple. We can see the button, empty list and there is no loader, this is regulated by default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c854964c7eec36392a44dfbd138148be/href">https://medium.com/media/c854964c7eec36392a44dfbd138148be/href</a></iframe><p>Let’s process intents for our UI</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e570e35549873dd4d7b14a5f0af999/href">https://medium.com/media/74e570e35549873dd4d7b14a5f0af999/href</a></iframe><p>Delay function simulates network delay, getFriendsUseCase() is a domain layer UseCase to load the list of friends. FriendListIntent.ShowFriends(friends) is a desired side effect which is the system supposed to start after completing the task</p><p>This is what reducer will look like for our intents</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4be9de1be2c408ad8f014003dec14d43/href">https://medium.com/media/4be9de1be2c408ad8f014003dec14d43/href</a></iframe><p>Now we just have to connect it all to our UI layer and look at the result. The project itself and examples are public on <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI">GitHub</a>.</p><h3>State as sealed class</h3><p>Nothing stops us from making our state a set of classes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1633699fa8dbb28fd256cc4874d4f2d/href">https://medium.com/media/d1633699fa8dbb28fd256cc4874d4f2d/href</a></iframe><p>In this case initial state is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ade17b76f082db99f0abb93b6e3f83d/href">https://medium.com/media/4ade17b76f082db99f0abb93b6e3f83d/href</a></iframe><p>As for reducer, instead of copying it will create and give away Loading and FriendList classes.</p><p>It is important to remember that as functionality of such state grows, it will get more difficult to transfer state data between these screens. This approach is helpful when your UI has two or more independent screen states.</p><h3>Example 2: Observe streams of data</h3><p>We have worked out how intents start a task and return the result. but what if we need to subscribe to some data source (for example, a database or a timer) and update UI with every new information emit</p><h3>Extending functionality of MVI class</h3><p>In order to do it, you have to add a function which takes suspend function and keeps its Job object to control the set of executed tasks for specific intents.</p><p>Here is its short version</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1eda044f195b97803014a42d613dbe4/href">https://medium.com/media/d1eda044f195b97803014a42d613dbe4/href</a></iframe><p>You also can stop any task using taskId you provided for start</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba18ed65b6c6a357e20c9fdf107304e1/href">https://medium.com/media/ba18ed65b6c6a357e20c9fdf107304e1/href</a></iframe><p>Full implementation you can see <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI/blob/4f6dfea280043e822b6f692d6c6cae8cb8ee9fec/mvi/src/main/kotlin/com/mvi/mvi/mvi/Mvi.kt#L63">here</a></p><p>Let’s implement a small timer, here is what its contract will look like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/979f530736b79961f2e1a1824e31406a/href">https://medium.com/media/979f530736b79961f2e1a1824e31406a/href</a></iframe><p>Now you can start initial state for out MVI</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c7ee98adb57f9af93bf9b0f3ccddef/href">https://medium.com/media/37c7ee98adb57f9af93bf9b0f3ccddef/href</a></iframe><p>Reducer will be extremely simple</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d47a4e4a777f5e8fa9c200479761008/href">https://medium.com/media/9d47a4e4a777f5e8fa9c200479761008/href</a></iframe><p>Now let’s move on to processing side effects</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f15e8d49d9ba53560d57d62789256b4/href">https://medium.com/media/2f15e8d49d9ba53560d57d62789256b4/href</a></iframe><p>When timer start, we can use our new function observeFlow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8a89fecb59c8301d8ff88e1d0a3036/href">https://medium.com/media/2a8a89fecb59c8301d8ff88e1d0a3036/href</a></iframe><p>UpdateTimer affects only UI and doesn’t start side effects</p><pre>is TimerIntent.UpdateTimer -&gt; null</pre><p>TimeIsUp is not supposed to start side effects but has to notify the user that the count down has ended. To do it we have to start SingleEvent, and let’s add the function for this to MVI class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4f99a9aa17b8b254bc546c0b250ddea/href">https://medium.com/media/f4f99a9aa17b8b254bc546c0b250ddea/href</a></iframe><p>Now our intent can trigger it</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efe9cb75364d20090223dff1e869184e/href">https://medium.com/media/efe9cb75364d20090223dff1e869184e/href</a></iframe><p>And that’s all. What is left is to subscribe to all these events with UI and logic of the application will work, the example with subscription you can see <a href="https://github.com/ZadorozhnyiSemen/ComposeMVI/blob/main/app/src/main/java/com/mvi/example/timer/TimerScreen.kt">here</a></p><h3>TL;DR</h3><p>I tested the described approach in a production application with a large number of users and on screens with different degrees of complexity. I must notice, that this approach a certain number of problems and there are some ‘best practices’ which should be followed and can be automated to make it possible for several people to work comfortably with one code base.</p><p>These methods will be described in the next part</p><p><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-2-63f9734c7d5a">&lt;- Previous part</a> | <a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4-6c0e31bd5a15">Next part -&gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99d2e90d76ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI for Compose (Part 2)]]></title>
            <link>https://szadorozhnyi.medium.com/mvi-for-compose-part-2-63f9734c7d5a?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f9734c7d5a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 08:53:11 GMT</pubDate>
            <atom:updated>2022-08-26T08:57:32.351Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">Problems and benefits of MVVM</a></li><li><strong>Custom MVI</strong> (you are here)</li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">Practical examples, continued implementation</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4-6c0e31bd5a15">Automating/reducing boilerplate</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-5-d59980388d61">Best practices and conclusions</a></li></ul><h3>MVI in a nutshell</h3><p>Here are the things which conceptually distinguish MVI for MVVM</p><ul><li>All commands come as intents (don’t confuse them with android intent). Intents are events which come from the user and from the system.</li><li>Reducer. Reducer is responsible for processing all intents and modifying the state based on intent data</li><li>MVI is defined by contract, contract includes state, fixed set of intents and single events</li><li>The presence of state versions. When state changes, the old state is not discarded, but stored in the event chain. If you wish, you can return to the previous state without any problems. In my opinion, this feature is really optional. Within a year of using MVI, I had only one case when it was necessary to rollback to the previous state.</li><li>Single events — optional events which are not supposed to be processed by reducer, and they act only one time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxoEiTitcTZfIb7uG_3Z4A.png" /></figure><h3>Implementation of MVI</h3><h3>MVI Contract</h3><p>This part is quite simple, we have to create three interfaces State, Intent и SingleEvent</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f01a47182b6177bf620f9b37d1f09abe/href">https://medium.com/media/f01a47182b6177bf620f9b37d1f09abe/href</a></iframe><p>Each screen’s contract will be implemented through these interfaces.</p><h3>MVI processor</h3><p>We are going to extend ViewModel implementation and create an abstract class which works with our contact</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e91b30aac20e43682d28afdc53d4ed8/href">https://medium.com/media/9e91b30aac20e43682d28afdc53d4ed8/href</a></iframe><p>Don’t forget to add dependencies for ViewModel</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e610c477b287f7c4d1bfc32673da77/href">https://medium.com/media/c1e610c477b287f7c4d1bfc32673da77/href</a></iframe><h3>Receive intents</h3><p>Now we have to teach our MVI to receive and store intents. In order to do it you can use SharedFlow. The intents must be received in a separate coroutine so as not to block the execution flow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71bef34fe462469ef9690aa89c4e3e60/href">https://medium.com/media/71bef34fe462469ef9690aa89c4e3e60/href</a></iframe><h3>Handle intents</h3><p>To process incoming intents when initialising the MviProcessor class, you need to subscribe to the intent flow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e876e3343d46d4bb04f0e628629bf973/href">https://medium.com/media/e876e3343d46d4bb04f0e628629bf973/href</a></iframe><h3>Screen state</h3><p>To do this, you can define two fields — one will contain the initial state of the screen, and the other for the state that the intents modify.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28ef9be8cc9b6bf2bcc70e7479eabedf/href">https://medium.com/media/28ef9be8cc9b6bf2bcc70e7479eabedf/href</a></iframe><p>initialState() function will be implemented by the successors of our MVI, and each screen defines its own initial state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d462dc716cbf12ba4d66bfa118b8c146/href">https://medium.com/media/d462dc716cbf12ba4d66bfa118b8c146/href</a></iframe><p>During initialisation the screen will take the initial state, successors cannot change it directly, this is the task of incoming intents.</p><h3>Reduce state</h3><p>Operation Reduce is really simple. Intent and state are received, and the result is new state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e46706a5d6a332f6204c0e86b19ca7/href">https://medium.com/media/f1e46706a5d6a332f6204c0e86b19ca7/href</a></iframe><p>Change of state will be available only for our MVI using interface</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c93dd8225baea9f159cb541f1a95d4d/href">https://medium.com/media/6c93dd8225baea9f159cb541f1a95d4d/href</a></iframe><p>Let’s combine these two operations</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfff662266a31a91a6555e8a82e4c954/href">https://medium.com/media/bfff662266a31a91a6555e8a82e4c954/href</a></iframe><p>Now let’s add a call to this function in the processing of intents</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e143ebd0c5dd019be050a171ecf92b/href">https://medium.com/media/97e143ebd0c5dd019be050a171ecf92b/href</a></iframe><h3>Side effects</h3><p>Any intent is able to trigger one or several side effects as Intents. For instance, changing the text in the search bar launches a request to the backend for the entered query.</p><p>Some intents do not trigger side effects and it must be considered.</p><p>The function responsible for this will be the one which receives an intent and current state of the screen and returns an optional side effect, which will also be an intent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49584f2fbb60aabaa1982456da4a7dda/href">https://medium.com/media/49584f2fbb60aabaa1982456da4a7dda/href</a></iframe><p>and if handleIntent has return something, you have to start coroutine for new intent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f670a6c9975b01e85ac2215545521d3/href">https://medium.com/media/0f670a6c9975b01e85ac2215545521d3/href</a></iframe><p>Now in order to create a screen with MVI, we have to define contract and override 3 methods of MVI class.</p><p>It’s not a full implementation just yet, additional ways for sending SingleEvent and subscribing to Flow will be described in the next part.</p><p><a href="https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25">&lt;- Previous part</a> | <a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">Next part -&gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f9734c7d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI for Compose (Part 1)]]></title>
            <link>https://szadorozhnyi.medium.com/mvi-for-compose-part-1-ece0654bc25?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece0654bc25</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvi]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 08:43:07 GMT</pubDate>
            <atom:updated>2022-08-26T08:56:40.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*99X9Vnairgq76pqC" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li><strong>Problems and benefits of MVVM</strong> (you are here)</li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-2-63f9734c7d5a">Custom MVI</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-3-99d2e90d76ef">Practical examples, continued implementation</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-4">Automating/reducing boilerplate</a></li><li><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-5-d59980388d61">Best practices and conclusions</a></li></ul><p>Normally, when you develop a mobile application, it is necessary to make a number of technical decisions, such as which technology stack to choose, how to organise code review and work in a team, and what to do to eventually make the project grow without increasing amount of time spent on changes and make onboarding help new people understand and accept rules in a team faster.</p><p>About a year ago our project entered the European market and we made a decision to establish these rules. One of the changes was introduction of Jetpack Compose into our application. We started to use Compose together with Android ViewModel, which provides helpful functionality out of the box, but the level of freedom it could give didn’t suit us. The solution was to write our own MVI implementation based on ViewModel in order to accelerate the development process in the future and establish the rules for employees in the mobile department to follow when developing our application.</p><p>In this article, I am going to share the problems we found while working with Android ViewModel and the solution, which we developed for Jetpack Compose.</p><p><strong>DISCLAIMER:</strong> The implementation described in this article is the result of work on a production project with certain requirements. The code and implementation are not a silver bullet and can be modified for different cases or even written in another way.</p><h3>ViewModel usage and problems</h3><p>Briefly speaking, there are no major problems. The tool is fully suitable for working with Compose, state storing and user actions processing on the screen. The thing that did not suit me when working with ViewModel:</p><ul><li>Variety of different observable data holders (LiveData’s, single LiveData, StateFlow, MutableState)</li><li>A large number of functions inside ViewModel and violation of Single responsibility principle.</li><li>Parallel and simultaneous update of UI state from anywhere in ViewModel</li></ul><p>Let’s have a closer look</p><h3>Different observable data holders</h3><p>Currently, there are a few options to subscribe for screen state change.<br>Here is a little about their pros and cons.</p><h4>Several LiveData containers</h4><p>Pros: It is a convenient approach for describing the state of different parts screens, each LiveData container contains a certain type of data and triggers the update of only the necessary screen components.</p><p>Cons: ViewModel contains a large amount of data and a few places where single LiveData can change. Different LiveData change independently of each other and can lead to inconsistent UI.</p><p>Single events require a custom <a href="https://proandroiddev.com/android-singleliveevent-redux-with-kotlin-flow-b755c70bb055">SingleLiveEvent implementation</a>.</p><p>Subscription is required in Composable function for each LiveData container.</p><h4>Single LiveData state</h4><p>It basically has the same problems as several LiveData, but what is different now is that there is one LiveData now and it contains the whole screen state, you can forget about a large number of LiveData fields and multiple subscriptions at @Composable function.</p><h4>StateFlow</h4><p>It is similar to a single LiveData distance, with the only difference being is that it doesn’t know anything about lifecycle of Activity/Fragment and requires additional steps in @Composable. It is described quite well in <a href="https://medium.com/androiddevelopers/repeatonlifecycle-api-design-story-8670d1a7d333">Manuel Vivo’s article</a>.</p><h4>MutableState</h4><p>It is an observable container for working with recomposition Compose. It is easier to subscribe to it from UI, but it loses all the advantages of Flow api. There is also a problem with ViewModel becoming dependant on Compose library.</p><p>If usage is not limited by static analisys tools your project might end up with every single approach above, which later will take time to refactor.</p><h3>A large number of functions inside ViewModel and violation of Single responsibility principle.</h3><p>The MVVM approach does not regulate writing functions inside ViewModel in any way. Without regulatory engineering practices in all view models, you are going to see multiple public and private functions which perform several things at once, and how side effects update the state of your UI. In the case of RxJava and using Subject your code can become a labyrinth of asynchronous events. Debugging such code is real bet very energy consuming.</p><p>In order to fix these problems, one has to separately discuss engineering practices with the team. However, if the code does not regulate its own writing and there are no tools for static program analysis, over time ViewModel will become a place which is going to be difficult for one to sort out.</p><p>At the same time. ViewModel can violate single responsibility principle. Apart from storing screen state, it is also an interface for running operations and changing screen state.</p><h3>Simultaneous UI update in ViewModel</h3><p>If screen state is declared as single class then the more complex the screen logiс is. the more methods are involved in changing UI state. In this case the approach with several LiveData makes maintenance easier as the code shows what exactly changes state UI. With most uni directional flow approaches there is one state and it is affected by all operations. Debugging access to fields can be helpful. but it become a routine task due to the presence of Race condition.</p><p>So, does ViewModel have any benefits? The answer is yes. Its ability to outlive (survive) UI, usage of SavedStateHandle, and presence of ViewModelScope are three features which ViewModel has and which are going to help us implement MVI paradigm.</p><p>More about using them in my next article!</p><p><a href="https://medium.com/@szadorozhnyi/mvi-for-compose-part-2-63f9734c7d5a">Next part -&gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece0654bc25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Инструменты тестирования Android приложений. Часть 4]]></title>
            <link>https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-4-d426f39d5ab6?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/d426f39d5ab6</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[proguard]]></category>
            <category><![CDATA[cardsmobile]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 11:37:16 GMT</pubDate>
            <atom:updated>2021-01-08T11:40:06.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KA2JT9VdRQ-B0r3w" /><figcaption>Photo by <a href="https://unsplash.com/@dariasha911?utm_source=medium&amp;utm_medium=referral">Daria Shatova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Содержание</strong>:</p><ul><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-87a6d6a9e817">Часть 1. Android приложение: что это и как с этим работать</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-2-4107dc748d0f">Часть 2: ADB</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-3-e347a621a3bd">Часть 3: Logcat</a></li><li><em>(Вы здесь) </em>Часть 4: ReTrace</li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-5-caddda14f175">Часть 5: Побеждаем ANR с помощью ANRWatchdog</a></li></ul><h3>ReTrace</h3><p>В теме про Logcat я говорил, что у Android приложений есть несколько видов сборки. Два стандартных и обязательных из них — это <em>“debug”</em> и <em>“release”</em> (на некоторых проектах их может быть больше).</p><p>Вот два основных отличия этих сборок:</p><ol><li><strong>“release” сборка обфусцируется</strong></li></ol><p>Обфускация — это переименование исходного кода, которое усложняет читаемость исходного когда и сокращает размер файлов. Так, например, если класс на Java был назван “com.example.MyClazz”, то после обфускации он превратится в что-то вроде “a.b.cсс”.</p><p>Когда разработчик запускает “release” сборку, система сборки создает apk файл с исходным кодом и файл mapping.txt. Последний файл содержит “перевод” файлов до и после обфускации, если брать наш пример, то в нем будет следующая строка:</p><p>com.example.MyClazz &lt;-&gt; a.b.ccc</p><p>Учитывайте, что обфускация происходит на этапе сборки релизной версии apk, и это полностью автоматизированный процесс. Результат будет таким же сюрпризом для разработчиков, как и для тестировщиков.</p><p>Хорошо и удобно хранить все сборки проекта на удаленном хранилище, к которому QA специалисты имеют доступ. И туда же загружать вместе с релизным APK его маппинг, чтобы все могли найти файл, который может развернуть обфускацию и сделать код снова читаемым.</p><p><strong>2. на “release” отключен Logcat</strong></p><p>Я уже упоминал выше, что мы не имеем возможности посмотреть логи пользователя из Logcat напрямую, так как Logcat не ведет журнал на “release” версии. Но на многих проектах обходят это условие и немного переписывают внутренний логгер так, чтобы он собирал эти данные локально и хранил их в защищенном месте внутри приложения. В этом случае, если пользователь захочет отправить отчет об ошибке разработчикам, на девайсе создастся файл, где будут собраны все логи на момент ошибки и, например, все логи за пять минут до ошибки. Пользователь может отправить этот файл в службу поддержки.</p><p>Но есть одна сложность: из-за той самой обфускации логи превращаются в абракадабру и прочитать их становится невозможным. Если к вам попали логи с обфусцированной ошибкой, вероятнось того, что вы сможете понять что именно произошло, крайне мала. <br> <br> И тут на сцену выходит еще один инструмент, который поможет в переводе абракадабры — <strong><em>ReTrace</em></strong>. Это утилита, которая принимает на вход обфусцированные логи с ошибкой и mapping.txt файл и “переводит” их в читаемый вид.</p><p>Найти деобфускатор можно в папке “Preferences → Android SDK → Android SDK location:” дальше перейти в tools/proguard/lib и запустить proguardui.jar.<br> У proguard приятный GUI, что бывает редко. В запущенной программе надо открыть вкладку <em>ReTrace</em>, загрузить туда mapping.txt и скопипастить обфусцированный стэк вызовов функций ошибки (или любых логов). После деобфускации вы получите красивые логи, какими вы можете увидеть их в “debug” версии приложения.<br> <br> Понимание принципа работы обфускации и метода возвращения ее в первоначальный вид очень расширяет кругозор. Разумеется, это не ежедневный кейс, с которым вам придется столкнуться. Но, если из саппорта придет странная ошибка, у вас будет знание о том, как с ней разобраться: с помощью каких инструментов все это привести в человеческий вид и как понять, что произошло на момент ошибки. Что, в свою очередь, поможет быстрее ее воспроизвести и грамотнее оформить отчет.</p><p>В следующей части мы разберемся с тем, что такое ANR и как находить и локализировать проблему “лагов” в приложениях.</p><p>← <a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-3-e347a621a3bd">Предыдущая часть</a> | <a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-5-caddda14f175">Следующая часть</a> →</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d426f39d5ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Инструменты тестирования Android приложений. Часть 5]]></title>
            <link>https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-5-caddda14f175?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/caddda14f175</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[cardsmobile]]></category>
            <category><![CDATA[anr]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 11:36:22 GMT</pubDate>
            <atom:updated>2021-01-08T11:40:34.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ajPWDFT_uLxXz2fG" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Содержание</strong>:</p><ul><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-87a6d6a9e817">Часть 1. Android приложение: что это и как с этим работать</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-2-4107dc748d0f">Часть 2: ADB</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-3-e347a621a3bd">Часть 3: Logcat</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-4-d426f39d5ab6">Часть 4: ReTrace</a></li><li><em>(Вы здесь) </em>Часть 5: Побеждаем ANR с помощью ANRWatchdog</li></ul><h3>Побеждаем ANR с помощью ANRWatchdog</h3><p>Если вы работаете на Windows и запустите несколько приложений, то их все можно увидеть в Диспетчере задач: под каждое приложение создается свой процесс, который можно завершить в любой момент.</p><p>Android работает по схожему принципу: каждое приложение в системе Android живет на своем процессе, у процесса есть своя выделенная память под нужды приложения и несколько потоков выполнения (Threads).</p><p>Потоки приложения нужны, чтобы делать несколько вещей одновременно, например, загружать электронную книгу и показывать анимированный статус загрузки.</p><p>Потоки приобрели свою популярность при создании многоядерных процессоров. Если в работе участвует только одно ядро, то приложение может иметь несколько потоков, но это будет псевдопараллелизм — потоки будут конкурировать за активное состояние и перебивать друг друга (на предыдущем примере: анимация будет зависать, пока она висит, загружается книга). На всех же современных телефонах все выполняется параллельно.</p><p>Важно знать, что у Android (и у многих других платформ) есть специальный поток, который занимается только отрисовкой UI и анимациями, он называется “Main Thread”.</p><p>Очень часто бывает, что разработчик забывает перевести тяжеловесную операцию на другой поток, и она начинает выполнятся на Main потоке. И из-за этого приложение визуально начинает подвисать.</p><p>Если такая ситуация случается и операция занимает очень много времени (например, работает сложный алгоритм, который ищет все словосочетания в файле размером в несколько гигабайт), то приложение завершится с ANR (Application not responding). Вы точно встречались с подобной ситуацией — появляется диалоговое окно с текстом “Приложение &lt;название&gt; не отвечает”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt2J_mWO6aNE5vur1tgH4A.png" /></figure><p>Теперь вы знаете почему так происходит. :)</p><p>Понимание данного нюанса поможет быстрее найти первопричину этих зависаний и составить подробный багрепорт, который будет более информативным, чем простое: “Экран Х завис, когда пользователь открыл его”.</p><p>ANR штука противная: из-за зависания потока не идет логгирования и не понятно, что именно забило поток выполнения, а сама Android система не пишет это напрямую.<br> Бывает, если прийти с ANR к разработчику, он может просто отмахнуться или попытаться воспроизвести и, в случае неудачи — забить (зависит это напрямую от степени неравнодушности команды разработки). QA специалист может прийти ANR к разработке примерно понимая откуда растут корни и потребовать мониторинга ситуации. И тут есть много средств, как эту ситуацию контролировать, самая простая из них и легкая в реализации — использовать стороннюю библиотеку <a href="https://github.com/SalomonBrys/ANR-WatchDog">ANRWatchdog</a>.</p><p>ANRWatchdog работает по следующему принципу: запускается отдельный поток, который через фиксированные периоды времени проверяет доступен ли Main поток. Если нет, то Watchdog кидает ошибку, в которой собирает информацию по всем активым потокам. Затем крашит приложение и выводит в логи информацию о том, что именно блокирует Main поток (вплоть до строчки в коде).</p><p>Прелесть этой библиотеки в том, что она хорошо конфигурируется — период проверки может меняться, библиотека может не крашить приложение, а отправлять логи на внешние трекеры, на которые потом можно ссылаться в отчетах об ошибке. С точки зрения разработки, ее внедрение займет два часа в худшем случае. Так что, если вы не еще ее не используете, то обсудите возможность ее внедрения с командой. Это та вещь, которая поможет улучшить производительность вашего приложения.</p><p>Еще бывают случаи, что подвисание UI может присутствовать, но не достигает критичных значений (Watchdog не отправляет ошибку, но UI заметно подвисает), в этом случае можно использовать встроенные в инструменты разработчика опцию <strong><em>Profile GPU rendering</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21oPPUFBTLovWWjLWfTacQ.png" /></figure><p>Она позволяет выводить на экран статистику по скорости отрисовки и обновления UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fz46fhKeoSVkJo_iM3esA.png" /></figure><p>Каждый вертикальный прямоугольник — это один кадр отрисовки. На Android девайсах 60fps (кадров в секунду) считается эталонным для человеческого восприятия. Если поделить секунду на 60 то получится, что один кадр должен выполняться максимум за 16.6 мс. Этот временной предел показывает горизонтальная зеленая линия.</p><p>Если вертикальный прямоугольник поднимается выше зеленой линии, значит время отрисовки кадра длилось дольше эталонного. То есть, если при загрузке экрана каждый кадр отрисовывается за 160 мс, то вместо 60 кадров в секунду мы получаем 50, а это уже будет заметно для глаз пользователя. Можно описать диагностику проще: “чем больше прямоугольники, тем хуже пользовательский опыт”.</p><p>Если такая ситуация встречается часто и у бизнесса есть фокус на улучшении перфоманса, то можно сконфигурировать Watchdog так, чтобы он отправлял отчеты при малых значениях и точечно устранять проблемы. Но эти пункты остаются на усмотрение команды и бизнеса: иногда можно акцентировать внимание на проблеме, но не трубить тревогу.</p><p>← <a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-4-d426f39d5ab6">Предыдущая часть</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caddda14f175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Инструменты тестирования Android приложений. Часть 3]]></title>
            <link>https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-3-e347a621a3bd?source=rss-2a1c1b0a9813------2</link>
            <guid isPermaLink="false">https://medium.com/p/e347a621a3bd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cardsmobile]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[logcat]]></category>
            <dc:creator><![CDATA[Semyon Zadoroznyi]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 11:31:14 GMT</pubDate>
            <atom:updated>2021-01-08T11:39:37.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pasq1gSOfHLlhofO" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Содержание</strong>:</p><ul><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-87a6d6a9e817">Часть 1. Android приложение: что это и как с этим работать</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-2-4107dc748d0f">Часть 2: ADB</a></li><li><em>(Вы здесь) </em>Часть 3: Logcat</li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-4-d426f39d5ab6">Часть 4: ReTrace</a></li><li><a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-5-caddda14f175">Часть 5: Побеждаем ANR с помощью ANRWatchdog</a></li></ul><h3>Logcat</h3><p>Наверное, самый базовый инструмент, который используют Android разработчики и QA специалисты при работе с Android.</p><p>В ходе написания кода разработчики выводят в консоль промежуточные результаты работы приложения в виде текстовых строк. Обычно здесь указывается информация о том, в какой момент и что делает приложение. За вывод этих данных отвечает встроенный журнал событий — Logcat.</p><p>С помощью Logcat можно узнать, какие запросы уходили на бэкенд, что отвечал бэкенд, какие данные сохранялись в базу данных и многое другое.<br> Самое главное, что дает Logcat — выводит стэк вызовов функций, в случае если произошла ошибка и приложение упало. Обычно имменно этот стэк вызовов копируется и вместе с условиями воспроизведения вставляется в баг репорт.</p><p>Если вы впервые слышите про Logcat и не понимаете, как читать из него данные, самый простой выход — <a href="https://developer.android.com/studio?hl=zh-cn">скачать Android Studio</a>, включить <a href="https://remontka.pro/developer-mode-android/">“Режим разработчика”</a> на своем тестовом телефоне и подключить по USB девайс к вашему ПК. В Android Studio снизу вы увидите вкладку Logcat, которую надо будет открыть, а потом выбрать девайс и приложение, которое вы тестируете.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQP_oznNcXyRIqKbiJOdhA.png" /></figure><p>Приятный бонус заключается в том, что Logcat можно настроить под задачу: это позволяет делать вкладка “Уровень логгирования”, где можно отслеживать, например, только ошибки. А также можно выводить информацию в журнал по ключевым словам с помощью регулярных выражений.</p><p>Стоит упомянуть, что здесь вам также пригодятся знания <em>adb</em>, ведь события из Logcat можно быстро собрать, прописав в консоли “adb logcat”. Приятный бонус!</p><p>Однако есть небольшой нюанс: как вы, вероятно, знаете, приложение может быть собранно в друх видах: <br> <em>“debug”</em> (для тестирования и разработки) и<em> “release”</em> (для релизов в маркет и поставки приложения конечному пользователю).<br> Важно учитывать, что если приложение находится в “release” сборке, то Logcat не будет иметь доступ к процессу приложения (в соответствии с требованиями безопасности маркетплейса), если не установлены специальные флаги, позволяющие это обойти. В связи с чем и журнал пользовательских логов для такого приложения будет недоступен.</p><p>Подводя итог, можно сказать, что Logcat — это самый полезный повседневный инструмент. Logcat поможет понять, когда в приложении что-то идет не так. Весь ход выполнения программы отражен в логах и вам как QA инженеру не обязательно знать языки программирования, чтобы понять, что бизнес требования не соответствуют ожидаемому поведению приложения. Чем больше вы будете знать свое приложение, тем больше профита будет приносить чтение логов. А по стэку ошибки вы сможете “ставить диагноз” эффективнее и давать больше полезной информации в баг репорте.</p><p>А в следующей части мы поговорим про особенности сборки Android приложений и как работать с обфусцированными логами.</p><p>← <a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-2-4107dc748d0f">Предыдущая часть</a> | <a href="https://szadorozhnyi.medium.com/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-android-%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9-%D1%87%D0%B0%D1%81%D1%82%D1%8C-4-d426f39d5ab6">Следующая часть</a> →</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e347a621a3bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>