<?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 Khayal Sharifli on Medium]]></title>
        <description><![CDATA[Stories by Khayal Sharifli on Medium]]></description>
        <link>https://medium.com/@khayalsharifli?source=rss-27e900aa10e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8XRPJ-_6zUhy-8qwe5_THA.jpeg</url>
            <title>Stories by Khayal Sharifli on Medium</title>
            <link>https://medium.com/@khayalsharifli?source=rss-27e900aa10e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:28:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khayalsharifli/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[ABB Mobile — Android Compose Architecture with Ticketing project]]></title>
            <link>https://khayalsharifli.medium.com/abb-mobile-android-compose-architecture-with-ticketing-project-2584078e282b?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2584078e282b</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 06:34:28 GMT</pubDate>
            <atom:updated>2026-06-05T06:39:07.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, in this article I will explain to you the general architecture we implemented for Jetpack Compose within <a href="https://abb-bank.az/">ABB Bank</a> after 2–3 quarters of research and a lot of trial and error. Please note that this is not the final version, we are still working on this process to make it the best for developers and customers.</p><p>Before we begin, I would like to thank all the team members who contributed to this long process, especially <a href="https://www.linkedin.com/in/raul-aydabekov-12710217a/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base%3BJkFwg6FBQ9GpTEL44dwcjA%3D%3D">Raul Aydabekov</a> and <a href="https://www.linkedin.com/in/aykhn-dev/">Aykhan Valiyev</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ka48kjEXTzwx1BDOIY9fFA.png" /></figure><p>Let’s first talk about how the process started. In the 3rd or 4th quarter of 2025, I was given a technical assignment to research Jetpack Compose and adapt it to our current code structure. The topic was interesting to me because although I had experience with Compose in the projects I wrote for myself, I had never done this type of large-scale research. Let’s take a look at the big picture of our architecture without further ado, and then analyze all the code samples from the <a href="https://abb-bank.az/xeberler/olkemizde-ilk-indi-aviabiletler-de-digitravel-le-abb-mobile-tetbiqinde-alinir">Ticketing project</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHbT2ryfPp8uuN-sXCZ82w.png" /></figure><p>Let’s break down the big picture and divide our article into parts, going from smallest to largest.</p><ul><li>Widget</li><li>ScreenContent</li><li>Screen</li><li>Fragment</li><li>ViewModel &amp; Events &amp; State</li></ul><h4>Widget</h4><p>Let’s start by solving the big picture. The smallest part of our game is a grouping of several similar components on our screen. We call this a widget. To make the point, let’s look at the following code example.</p><pre>internal data class DashboardServicesSectionState(<br>    val services: ImmutableList&lt;ServiceItemState&gt;,<br>    val isLoading: Boolean,<br>    val isLoaded: Boolean,<br>    val contentState: DashboardServicesContentState,<br>)<br><br>@Composable<br>internal fun DashboardServicesSection(<br>    stateReader: () -&gt; DashboardServicesSectionState,<br>    onServiceClick: (String) -&gt; Unit,<br>    onRetryClick: () -&gt; Unit,<br>) {<br>    val isLoading = stateReader.read { isLoading }<br>    val isLoaded = stateReader.read { isLoaded }<br>    val services = stateReader.read { services }<br><br>    when {<br>        isLoading -&gt; {<br>            DashboardServicesShimmer()<br>        }<br><br>        services.isEmpty() &amp;&amp; isLoaded -&gt; {<br>            DashboardServicesEmptyState(onRetryClick = onRetryClick)<br>        }<br><br>        services.isNotEmpty() -&gt; {<br>            val contentStateReader = stateReader.focusOn { contentState }<br>            DashboardServicesContent(<br>                stateReader = contentStateReader,<br>                onServiceClick = onServiceClick,<br>            )<br>        }<br>    }<br>}</pre><p>Please note that in this article we are looking at the general architecture, so I will not go into detail about the stateReader model, but you can read more about it in <a href="https://medium.com/@ayxan.ev/best-way-of-managing-compose-recompositions-1d0cb62e5c8a?postPublishedType=repub">Aykhan Valiyev’s article</a>, but in short, we use it to minimize re-composition. The other parts are simple, showing either empty, loading, or full data in different screen states.</p><h4>ScreenContent</h4><p>Now let’s look at the other part, “TicketingDashboardScreenContent”. The main reason we split our screen logic into two is to keep our composable elements clean and use all the screen functionality. From the composable constructor, which we call “ScreenContent”, we simply take the events for button click actions and our state class and display the state in the UI. Let’s look at the following code example:</p><pre>@Composable<br>internal fun TicketingDashboardScreenContent(<br>    stateReader: () -&gt; TicketingDashboardScreenState,<br>    actions: TicketingDashboardActions,<br>    modifier: Modifier = Modifier,<br>) {<br>// Our Screen design <br>}</pre><p>As you can see, since our screen content doesn’t require heavy logic classes like viewmodel etc., we can preview it in the blink of an eye with simple test data and see the result of the composition we wrote without running it.</p><pre>@PreviewLightDark<br>@Composable<br>private fun TicketingDashboardScreenContentPreview() {<br>    ExampleTheme {<br>        TicketingDashboardScreenContent(<br>            stateReader = { TicketingDashboardScreenState.INITIAL },<br>            actions = TicketingDashboardActions(),<br>        )<br>    }<br>}</pre><h4>Screen</h4><p>“Screen” Composes are where we observe our state and effects, while pure Compose is where we populate “ScreeContent”, let’s look at a code example to understand what I mean.</p><pre>@Composable<br>internal fun TicketingDashboardScreen(<br>    viewModel: TicketingDashboardViewModel,<br>    onBackClick: () -&gt; Unit,<br>    onFromFieldClick: () -&gt; Unit,<br>    onToFieldClick: () -&gt; Unit,<br>) {<br>    val uiState by viewModel.collectAsState()<br><br>    viewModel.collectSideEffect { effect -&gt;<br>        when (effect) {<br>            is TicketingDashboardEffect.NavigateBack -&gt; onBackClick()<br>            is TicketingDashboardEffect.NavigateToFromSelection -&gt; onFromFieldClick()<br>            is TicketingDashboardEffect.NavigateToToSelection -&gt; onToFieldClick()<br>            is TicketingDashboardEffect.NavigateToDateSelection -&gt; onDateFieldClick()<br>        }<br>    }<br><br>    val actions = TicketingDashboardActions(<br>        onBackClick = viewModel::onBackClick,<br>        onBannerClick = viewModel::onBannerClick,<br>        onServiceClick = viewModel::onServiceClick,<br>    )<br><br>    TicketingDashboardScreenContent(<br>        stateReader = { uiState },<br>        actions = actions<br>    )<br>}</pre><p>If we look at our code example above, we get the viewModel and click actions from the constructor. In fact, instead of getting the viewModel from the constructor, we could have just injected it inside @Composable. The main reason we continued like this was that we used .xml instead of jetpack compose navigation for navigation. We will get to the reason in the section below. There is no need to use any @Preview in our composable in this section, because we already did @Preview in the underlying ScreenContent and used our pure composable function. This is just for combining the puzzles we have, pure compose, and viewModel.</p><h4>Fragment</h4><p>Now we come to an interesting question: why do we enclose two compositions with one fragment at the same time? What made us do this?</p><p>Actually, the game was very simple, the reason we did this was to continue with navigation.xml, yes, you heard right, we have turned away from using Jetpack Compose’s pure navigation system for now, and as I mentioned, this architecture is a structure that was formed over 2–3 quarters, in our first compose, we were actually using NavHost and Jetpack Navigation as follows</p><pre>NavHost(<br>        navController = navController,<br>        startDestination = startDestination<br>    ) {<br>        exampleGraph1(<br>            navController = navController,<br>            viewModelFactory = viewModelFactory,<br>        )<br><br>        exampleGraph2(<br>            navController = navController,<br>            viewModelFactory = viewModelFactory<br>        )<br><br>        exampleGraph3(<br>            navController = navController,<br>            viewModelFactory = viewModelFactory<br>        )<br>    }</pre><p>But we encountered unexpected bugs and these bugs were hidden under the library code, for example, when users pressed the back button twice quickly, they encountered a space error, this is one of the famous bugs of composable (<a href="https://stackoverflow.com/questions/79303253/navigation-back-causes-a-white-screen-overlay-on-previous-destination-in-jetpack">you can see more details here</a>) and there are a few other points, it is true, the library owners worked hard to fix bugs and improve their code in each version, everything was good on this side, but at the end of the day <a href="https://play.google.com/store/apps/details?id=iba.mobilbank&amp;hl=en">ABB Mobile</a> was a banking application with over 5 million downloads and even small problems like this were serious user loss and negative reviews, so we stuck to old habits and continued with the navigation.xml that we have been using without problems for years and that compiles all our code, but we are open to changes and improvements, since we are building a game for this setup in the future, we can easily switch to composite navigation at any time by deleting the fragment and navigation.xml files. Now let’s see what I mean by looking at our Fragment example.</p><pre>internal class TicketingDashboardFragment : Fragment() {<br><br>    private val viewModelFactory by lazy {<br>        TicketingComponentHolder.component.viewModelFactory<br>    }<br><br>   override fun onCreateView(<br>        inflater: LayoutInflater,<br>        container: ViewGroup?,<br>        savedInstanceState: Bundle?,<br>    ): View = ComposeView(requireContext()).apply {<br>        setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)<br>        setContent {<br>            ExampleTheme {<br>                TicketingDashboardScreen(<br>                    viewModel = viewModel,<br>                    onBackClick = ::onBackClick,<br>                    onFromFieldClick = ::onFromFieldClick,<br>                    onToFieldClick = ::onToFieldClick,<br>            }<br>        }<br>    }<br><br>    private fun onFromFieldClick(workflowId:String) {<br>        val direction = TicketingDashboardFragmentDirections.actionDashboardToFlightsResult(<br>            workflowId = workflowId<br>        )<br>        findNavController().navigateSafely(direction)<br>    }<br>}</pre><p>If we look at the code example above, our Fragment layer is actually very simple, we just place our viewModel and pass it as the content of “TicketingDashboardScreen” inside onCreateView and additionally pass our navigation functions like onFromFieldClick inside “TicketingDashboardScreen” as Unit. While the game looks very complex, it is very simple when broken down into parts.</p><h4>ViewModel &amp; Events &amp; State</h4><p>Let’s now look at the 3 interesting components of our game. First of all, let me say that it is easy to debug and the code structure is suitable for us. In this section, we chose <a href="https://github.com/orbit-mvi/orbit-mvi">Orbit MVI</a>. It seemed like a waste of time to write something for a structure that already exists in practice and is used by many, so we just implemented Orbit and started using it.</p><pre>@Stable<br>internal class TicketingDashboardViewModel @AssistedInject constructor(<br>    @Assisted private val savedStateHandle: SavedStateHandle,<br>    private val exampleUseCase: TicketingDashboardExampleUseCase,<br>) : ViewModel(), ContainerHost&lt;TicketingDashboardScreenState, TicketingDashboardEffect&gt; {<br>  <br>   fun onBackClick() = intent { postSideEffect(TicketingDashboardEffect.NavigateBack) }<br><br>   fun onReloadServices() = intent {<br>          reduce { state.copy(isServicesLoaded = false) }<br>          loadAvailableServices()<br>      }<br>}</pre><pre>internal data class TicketingDashboardScreenState(<br>    val isServicesLoading: Boolean = false,<br>    val services: ImmutableList&lt;ServiceItemState&gt; = persistentListOf(),<br>    val ..... example, example, example,<br>) </pre><pre>@Immutable<br>internal sealed interface TicketingDashboardEffect {<br>    data object NavigateBack : TicketingDashboardEffect<br>    data object NavigateToMore : TicketingDashboardEffect<br>    data class OnClickService(val type: String) : TicketingDashboardEffect<br>}</pre><p>Looking at the codes above, this is actually a simple MVI Orbit. In short, this is the game and we are still doing our best to make this game as playable as possible, there are still areas we need to improve and if there is any new development, I will share the information with you. I will add what I wrote myself and what I took from <a href="https://www.linkedin.com/in/aykhn-dev/">Aykhan Valiyev’s</a> sources so that you can analyze it in detail.</p><p><a href="https://github.com/khayalsharifli/pricetracker">Price Tracker application with this architecture</a></p><p><a href="https://medium.com/@ayxan.ev/best-way-of-managing-compose-recompositions-1d0cb62e5c8a?postPublishedType=repub">StateReader sample article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2584078e282b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Basics Part 1]]></title>
            <link>https://khayalsharifli.medium.com/jetpack-compose-basics-part-1-ccdc4f33e059?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccdc4f33e059</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 14:58:18 GMT</pubDate>
            <atom:updated>2025-11-11T14:58:18.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Knowledge is power</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98C7NFCE7xfp8BLUrUN2Nw.png" /></figure><p>Hi Guys, Compose is developing day by day and is presented to us with new value and improvements every time, while we sometimes write our codes one after another without knowing what is happening in the background and just execute our code, and see the UI we wrote on our phone, make sure that the business logic and APIs are working correctly and send it to the users for use. Okay, so what did we do wrong in this process, let’s see:</p><blockquote>Are the recompostion counts really correct in our app, do we understand what it is and check it every time we create a new @Composable function?</blockquote><h4>Recomposition</h4><p>Let’s first learn what it is, then why we measure it, and then how we measure it (This is the golden rule of deep learning, to me, to ask these questions to something you’re learning: what?, why?, how?)</p><h4>What is recompostion?</h4><p>In simple terms, recompostion is the process of rebuilding our UI <a href="http://twitter.com/Composable">@Composable</a> function to reflect the new state every time the state changes, for example:</p><pre>@Composable<br>fun Counter() {<br>    // Declare mutable state for the counter value<br>    // &#39;remember&#39; ensures the state persists across recompositions<br>    // &#39;mutableIntStateOf(0)&#39; creates an observable integer state initialized to 0<br>    // &#39;var count by&#39; uses delegate syntax to directly access the state value<br>    var count by remember { mutableIntStateOf(0) }<br>    <br>    Column(<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br>        Text(text = &quot;Simple Counter App Static Text&quot;, fontSize = 32.sp)<br><br>        // Display a Text composable showing the current count value<br>        // The string interpolation &quot;$count&quot; creates a data dependency<br>        Text(text = &quot;Count: $count&quot;, fontSize = 24.sp)<br><br>        // Increment the count state by 1<br>        // This state change triggers recomposition of the Counter and its children<br>        Button(onClick = { count++ }) {<br>            // The Button recomposes to show the &quot;Increment&quot; text<br>            Text(&quot;Increment&quot;)<br>        }<br>    }<br>}</pre><p>Now let’s take a bird’s eye view of what happens to this code every time our state changes and recomposition occurs. As we can see in the example, static UIs that are independent of state are simply skipped during recomposition.</p><pre>Counter() Composable<br>│<br>├─ remember { mutableIntStateOf(0) }     ← State is stored here<br>│<br>└─ Column(...)<br>    │<br>    ├─ Text(&quot;Simple Counter App Static Text&quot;)   ← 🟩 Static content<br>    │                                            NOT recomposed<br>    │<br>    ├─ Text(&quot;Count: $count&quot;)                    ← 🟦 Depends on &#39;count&#39;<br>    │                                            RECOMPOSES when &#39;count&#39; changes<br>    │<br>    └─ Button(onClick = { count++ })             ← 🟦 Triggers &#39;count&#39; change<br>         └─ Text(&quot;Increment&quot;)                    ← 🟩 Static content (doesn&#39;t recompose)</pre><h4>Why should we pay attention to Recompostion?</h4><p>Ah, now we come to the main issue, we saw that when recomposting, static x that is independent of the state is simply skipped, maybe it’s not doing it in our code right now?, maybe we are doing something wrong that we currently know is right and every state change costs us the entire UI to be rebuilt, many questions arose in our minds. Let’s first see the consequences of incorrect recomposting.</p><ol><li>Bad user experience UI freezes</li><li>Additional load on phone processor Non-fatal or crash in the background</li></ol><h4>How can we both correctly recompost and measure it?</h4><p>Let’s look at this code example, every time the button is touched, nothing will change in the UI, there will be many recompositions in the background, but each one will be skipped, because we did not use remember{ } here, unlike our first code example, and this will cause us to not preserve the state and recreate it with the initial value every time (This is just one of the bad examples, I will present you more bad and good examples below)</p><pre>@Composable<br>fun BadCounter() {<br>    // ❌ &#39;remember&#39; is NOT used here<br>    // The state is recreated on every recomposition<br>    var count = mutableIntStateOf(0)<br><br>    Column(<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br>        // 🟥 Static text - but it will be recomposed every time unnecessarily<br>        Text(text = &quot;Static Header&quot;, fontSize = 32.sp)<br><br>        // 🟥 Text that depends on &#39;count&#39; - will change as expected<br>        Text(text = &quot;Count: ${count.intValue}&quot;, fontSize = 24.sp)<br><br>        // 🟥 Button will also be rebuilt on every click<br>        Button(onClick = { count.intValue++ }) {<br>            Text(&quot;Increment&quot;)<br>        }<br>    }<br>}</pre><pre>BadCounter() Composable<br>│<br>├─ mutableIntStateOf(0)                          ← ❌ State is NOT remembered<br>│                                                   Recreated on EVERY recomposition<br>│<br>└─ Column(...)<br>    │<br>    ├─ Text(&quot;Static Header&quot;)                     ← 🟥 Static content BUT<br>    │                                               RECOMPOSES unnecessarily<br>    │                                               (whole function reruns)<br>    │<br>    ├─ Text(&quot;Count: ${count.intValue}&quot;)          ← 🟥 Depends on &#39;count&#39;<br>    │                                               RECOMPOSES but count resets<br>    │                                               to 0 each time<br>    │<br>    └─ Button(onClick = { count.intValue++ })    ← 🟥 Triggers recomposition<br>         └─ Text(&quot;Increment&quot;)                    ← 🟥 Also recomposes unnecessarily<br>                                                    (count never actually increments)</pre><p>Measuring this is actually very simple, just go to the Layout Inspector section within Android Studio and look at what happens in each state update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZamor_YhA50cMifew2bOQ.png" /></figure><h4>Now, let’s look at how we can optimize our own code with a collection of good and bad examples.</h4><ol><li>Always but always preserve the state with remember {}:</li></ol><pre>// ❌ WRONG - resets on every recomposition<br>var count = mutableStateOf(0)<br><br>// ✅ CORRECT - state is preserved<br>var count = remember { mutableStateOf(0) }</pre><p>2. If you are using List views, assign unique keys to each item:</p><pre>// ❌ WRONG - items can get mixed up<br>items.forEach { item -&gt;<br>    ItemCard(item)<br>}<br><br>// ✅ CORRECT - each item tracked with unique ID<br>items.forEach { item -&gt;<br>    key(item.id) {<br>        ItemCard(item)<br>    }<br>}</pre><pre>// ❌ WRONG - all items composed at once<br>Column {<br>    items.forEach { item -&gt; ItemCard(item) }<br>}<br><br>// ✅ CORRECT - only visible items are composed<br>LazyColumn {<br>    items(items, key = { it.id }) { item -&gt;<br>        ItemCard(item)<br>    }<br>}</pre><p>3. Do the calculations you want to do inside derivedStateOf (I’m sure this will add a lot of value to you and make the UI easier):</p><pre>// ❌ WRONG - recalculated on every recomposition<br>val isExpanded = list.size &gt; 10<br><br>// ✅ CORRECT - only recalculated when list.size changes<br>val isExpanded = remember { derivedStateOf { list.size &gt; 10 } }</pre><p>4. Explore the topic of Side Effects in depth (we will talk about this in the next section):</p><pre>// ❌ WRONG - API call happens on every recomposition<br>viewModel.fetchData()<br><br>// ✅ CORRECT - only called once<br>LaunchedEffect(Unit) {<br>    viewModel.fetchData()<br>}</pre><p>5. I used to make this mistake myself :))</p><pre>// ❌ WRONG - new Modifier on every recomposition<br>@Composable<br>fun MyCard() {<br>    Box(modifier = Modifier.padding(16.dp).fillMaxWidth()) { }<br>}<br><br>// ✅ CORRECT - Modifier passed as parameter<br>@Composable<br>fun MyCard(modifier: Modifier = Modifier) {<br>    Box(modifier = modifier.padding(16.dp)) { }<br>}</pre><p>6. Avoid using GlobalScope in Composed as in the Xml Fragment example.</p><pre>// ❌ WRONG - scope not created or memory leak<br>GlobalScope.launch { /* animation */ }<br><br>// ✅ CORRECT - tied to composable lifecycle<br>val scope = rememberCoroutineScope()<br>Button(onClick = {<br>    scope.launch { /* animation */ }<br>}) {<br>    Text(&quot;Animate&quot;)<br>}</pre><p>Bonus:</p><p>Compose Stability Analyzer is a must try, I’m putting the detailed github link and medium reference here, I tried it and it was a plugin that I really liked and thought worked, so I wanted to share it with you:</p><p>Github: <a href="https://github.com/skydoves/compose-stability-analyzer">https://github.com/skydoves/compose-stability-analyzer</a><br>Medium: <a href="https://proandroiddev.com/compose-stability-analyzer-real-time-stability-insights-for-jetpack-compose-1399924a0a64">https://proandroiddev.com/compose-stability-analyzer-real-time-stability-insights-for-jetpack-compose-1399924a0a64</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccdc4f33e059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Watch faces for your branding with Jetpack Compose]]></title>
            <link>https://khayalsharifli.medium.com/build-watch-faces-for-your-branding-with-jetpack-compose-14de72626055?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/14de72626055</guid>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[watches]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[watchface]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 07:31:50 GMT</pubDate>
            <atom:updated>2024-08-19T07:31:50.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4_Ko7Qbt51nji0XH9s_dg.png" /></figure><h4><strong>What is watch faces?</strong></h4><p>We use android os wrist watches in our daily life and we are limited to choose their watch screen with different templates according to our taste. Now let’s remove the restrictions and make everything according to our dream world or brand</p><h4><strong>About</strong></h4><ol><li>How we create custom watch faces in Android</li><li>Let’s use Jetpack Compose and let’s create watch faces with Canvas</li></ol><h4>Let’s start</h4><p>First, we have 2 ways to create custom watch faces, one way is with <a href="https://developer.samsung.com/watch-face-studio/user-guide/index.html">Watch Face Studio</a> and another way is to write Jetpack Compose codes.</p><ol><li>If you are creating custom watch face of your company easily then you can choose <a href="https://developer.samsung.com/watch-face-studio/user-guide/create.html">Watch Face Studio </a>because it is very easy :) It covers the basics of the tool including design layout, component selection and animation options. The guide also explains how to review and test your designs, manage resources, and prepare your watch face for distribution.</li><li>We have no limits for the development, like <a href="https://developer.samsung.com/watch-face-studio/user-guide/create.html">Watch Face Studio</a> in this way, let’s find out how to do it</li></ol><p><strong>1. The firstly we need to create Android Project for the watch:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDqO-KS0KKGY3tna7mSxKg.png" /></figure><p><strong>2. We need to add all implementation in the build.gradle.kt for this one you can follow this </strong><a href="https://github.com/Splitties/ComposeOClock"><strong>Github Repository</strong></a>, <strong>as like this</strong>:</p><pre>dependencies {<br>    coreLibraryDesugaring(Android.tools.desugarJdkLibs)<br>    implementation {<br>        project(&quot;:shared&quot;)()<br>        libs.compose.oclock.watchface.renderer()<br>        AndroidX.wear.watchFace.editor()<br><br>        platform(AndroidX.compose.bom)<br>        AndroidX.wear.compose.material()<br>        AndroidX.wear.compose.foundation()<br>        AndroidX.activity.compose()<br>        AndroidX.core.splashscreen()<br>        Splitties.systemservices()<br>        Splitties.toast()<br>    }<br>    androidTestImplementation {<br>        platform(AndroidX.compose.bom)<br>        AndroidX.compose.ui.testJunit4()<br>    }<br>    debugImplementation {<br>        platform(AndroidX.compose.bom)<br>        AndroidX.compose.ui.tooling()<br>        AndroidX.compose.ui.testManifest()<br>    }<br>}</pre><p>3. Create to Watch Face Service for declare in the Android Manifest file</p><pre>class SampleWatchFaceService : ComposeWatchFaceService(<br>    complicationSlotIds = emptySet(),<br>    invalidationMode = InvalidationMode.WaitForInvalidation<br>) {<br><br>    @Composable<br>    override fun Content(complicationData: Map&lt;Int, StateFlow&lt;ComplicationData&gt;&gt;) {<br>        WatchFaceSwitcher()<br>    }<br><br>    override fun supportedComplicationTypes(slotId: Int) = listOf(<br>        ComplicationType.RANGED_VALUE,<br>        ComplicationType.SHORT_TEXT<br>    )<br>}</pre><p>4. Finally you need to add View Content in “Content” function, it depends on your design or your dream words :), as like this Canvas watch face:</p><pre><br>@Composable<br>fun OClockCanvas(<br>    onTap: TapHandler? = null,<br>    onDraw: DrawScope.() -&gt; Unit<br>) {<br>    var lastDrawScope: DrawScope? by remember { mutableStateOf(null) }<br>    var lastOnTapScope: OnTapScope? by remember { mutableStateOf(null) }<br>    onTap?.let { handler -&gt;<br>        val tapEventHandlers = requireNotNull(TapEventHandlers.Local.current) {<br>            ErrorMessages.requiresOClockRootCanvas<br>        }<br>        tapEventHandlers.KeepHandler { event -&gt;<br>            when (val scope = lastOnTapScope) {<br>                null -&gt; false<br>                else -&gt; {<br>                    with(handler) {<br>                        scope.onTap(event)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>    val onDrawWithTaps: DrawScope.() -&gt; Unit = remember(onTap, onDraw) {<br>        when (onTap) {<br>            null -&gt; {<br>                lastDrawScope = null<br>                lastOnTapScope = null<br>                onDraw<br>            }<br>            else -&gt; fun DrawScope.() {<br>                if (lastDrawScope != this) {<br>                    lastDrawScope = this<br>                    lastOnTapScope = OnTapScopeImpl().also {<br>                        it.update(this)<br>                    }<br>                }<br>                onDraw()<br>            }<br>        }<br>    }<br>    DrawDelegate.Local.current.KeepDrawFunction(onDrawWithTaps)<br>}</pre><h4>Simple Imagination for watch o clock</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KL-K34rO57p0lcyWC_7NPg.png" /></figure><p>Thanks for reading in the next article, I want to talk more about this topic in my Github repo, i would like doing this in part 2 :)</p><p>I used this open-source urls:</p><p><a href="https://github.com/Splitties/ComposeOClock">Github Repository</a>, <a href="https://developer.android.com/training/wearables/watch-faces">Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14de72626055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Widgets With Jetpack Compose Glance]]></title>
            <link>https://medium.com/abb-innovation/creating-widgets-with-jetpack-compose-glance-8a30d996ec6f?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a30d996ec6f</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[glance]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 09:10:24 GMT</pubDate>
            <atom:updated>2024-02-26T12:48:09.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0T_3RX6kIvFHhnshnobZg.png" /></figure><p>What is Glance ?</p><p><strong>Jetpack Glance</strong> is a framework for creating <strong>small, lightweight, and efficient app widgets</strong> using <strong>Kotlin APIs</strong>. It is designed to be used for displaying information that users need to know at a <strong>glance</strong>.</p><p>How we create widgets with <strong>Jetpack Glance?</strong></p><p>Now we show step by step:</p><p><strong>Setup:</strong></p><p>Let’s add the dependencies in your app’s module based on the features you need.</p><pre>dependencies {<br>    // For Glance support<br>    implementation(&quot;androidx.glance:glance:1.0.0-rc01&quot;)<br>    <br>    // For AppWidgets support<br>    implementation(&quot;androidx.glance:glance-appwidget:1.0.0-rc01&quot;)<br><br>    // For Wear-Tiles support<br>    implementation(&quot;androidx.glance:glance-wear-tiles:1.0.0-alpha05&quot;)<br>}<br><br>android {<br>    buildFeatures {<br>        compose = true<br>    }<br><br>    composeOptions {<br>        kotlinCompilerExtensionVersion = &quot;1.1.0-beta03&quot;<br>    }<br><br>    kotlinOptions {<br>        jvmTarget = &quot;1.8&quot;<br>    }<br>}</pre><p><strong>Create Widget Receiver class</strong>:</p><pre>class MyAppWidgetReceiver : GlanceAppWidgetReceiver() {<br>    override val glanceAppWidget: GlanceAppWidget = MyAppWidget()<br>}</pre><p><strong>Create our Widget ui:</strong></p><pre>/* Import Glance Composables<br> In the event there is a name clash with the Compose classes of the same name,<br> you may rename the imports per https://kotlinlang.org/docs/packages.html#imports<br> using the `as` keyword.<br><br>import androidx.glance.Button<br>import androidx.glance.layout.Column<br>import androidx.glance.layout.Row<br>import androidx.glance.text.Text<br>*/<br>class MyAppWidget : GlanceAppWidget() {<br><br>    override suspend fun provideGlance(context: Context, id: GlanceId) {<br>        // Load data needed to render the AppWidget.<br>        // Use `withContext` to switch to another thread for long running<br>        // operations.<br><br>        provideContent {<br>            // create your AppWidget here<br>            MyContent()<br>        }<br>    }<br><br>    @Composable<br>    private fun MyContent() {<br>        Column(<br>            modifier = GlanceModifier.fillMaxSize(),<br>            verticalAlignment = Alignment.Top,<br>            horizontalAlignment = Alignment.CenterHorizontally<br>        ) {<br>            Text(text = &quot;Where to?&quot;, modifier = GlanceModifier.padding(12.dp))<br>            Row(horizontalAlignment = Alignment.CenterHorizontally) {<br>                Button(<br>                    text = &quot;Home&quot;,<br>                    onClick = actionStartActivity&lt;MainActivity&gt;()<br>                )<br>                Button(<br>                    text = &quot;Work&quot;,<br>                    onClick = actionStartActivity&lt;MainActivity&gt;()<br>                )<br>            }<br>        }<br>    }<br>}</pre><p><strong>Create </strong><strong>AppWidgetProviderInfo metadata:</strong></p><p>Create and define the app widget info in the <a href="http://twitter.com/xml/my_app_widget_info">@xml/my_app_widget_info</a> file.</p><pre>&lt;appwidget-provider xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:initialLayout=&quot;@layout/glance_default_loading_layout&quot;&gt;<br>&lt;/appwidget-provider&gt;</pre><p>Register the provider of the app widget in your AndroidManifest.xml file and the associated metadata file:</p><pre>&lt;receiver android:name=&quot;.glance.MyAppWidgetReceiver&quot;<br>    android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>    &lt;meta-data<br>        android:name=&quot;android.appwidget.provider&quot;<br>        android:resource=&quot;@xml/my_app_widget_info&quot; /&gt;<br>&lt;/receiver&gt;</pre><p>And do this we create our custom widgets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*AZE5oFndFp2YxXanZh62Pg.png" /></figure><p>Finally, I hope this was helpful for you, you can view all the code by linking to my <a href="https://github.com/khayalsherif/Glance"><strong>Github Repository</strong></a><strong>.</strong></p><p><strong>Sources used:</strong></p><p><a href="https://developer.android.com/jetpack/compose/glance/create-app-widget">https://developer.android.com/jetpack/compose/glance/create-app-widget</a></p><p><a href="https://medium.com/@daniel.atitienei/creating-widgets-with-jetpack-compose-glance-d27d7e9a54c1">https://medium.com/@daniel.atitienei/creating-widgets-with-jetpack-compose-glance-d27d7e9a54c1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a30d996ec6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abb-innovation/creating-widgets-with-jetpack-compose-glance-8a30d996ec6f">Creating Widgets With Jetpack Compose Glance</a> was originally published in <a href="https://medium.com/abb-innovation">ABB Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Custom Lint Rules in Android]]></title>
            <link>https://khayalsharifli.medium.com/writing-custom-lint-rules-in-android-edf6df7045fd?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf6df7045fd</guid>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[custom-rule]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:00:26 GMT</pubDate>
            <atom:updated>2024-02-26T12:48:49.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*V2EDFPlZSdQQSVyKn6I68w.png" /></figure><h3>About</h3><p>Hello, today we will talk about writing a custom lint rule. The first thing we need to know is why are we doing this, because Android Studio itself already has built-in lint rules and we already spend enough time writing code for the business side, so why waste time writing it?</p><ol><li>Why should we write custom lint?</li><li>Write a custom lint rule with a real example.</li></ol><h3>Why should we write custom lint?</h3><p><strong>(In my current experience, this is the main reason I see for writing custom lint rules, others may have)<br></strong>You have a large team and you have implemented certain rules for writing code within your company (for more readable and easy-to-understand code for everyone), but you don’t want to waste time on code reviews every time, and even if you look, you don’t want to waste time on code reviews to see if these rules are followed by developers. there will be moments, at this point writing custom lint comes into play and has a positive effect on both your time and your code. So let’s write a custom lint on a shared example.</p><h3>Write a custom lint rule with a real example.</h3><p>So now let’s write a custom lint rule with a real naming example and we’ll do it step by step.</p><ol><li><strong>Let’s create a new module called lint-rules for custom lint rules:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXkfZEKO5BUjgTZTgjERDg.png" /></figure><p><strong>2. Now we add implementations in lint-rules module’s build.gradle.</strong></p><pre>dependencies {<br>    def lint_version = &#39;30.1.0-alpha03&#39;<br>    compileOnly &quot;com.android.tools.lint:lint-api:$lint_version&quot;<br>    testImplementation &quot;com.android.tools.lint:lint-tests:$lint_version&quot;<br>}</pre><p><strong>3. Let’s understand custom lint class terms “Visitor,” “Issue,” and “Detector”</strong></p><p>3.1 Visitor: A visitor is a design pattern used to traverse and analyze the Abstract Syntax Tree (AST) of the source code. In the context of lint, a visitor is responsible for visiting different elements of the AST, such as classes, methods, expressions, or statements. It allows you to navigate the structure of the code and perform specific operations or checks on each visited element.</p><p>3.2 Issue: An issue represents a specific problem or rule violation that you want to detect in the codebase. It encapsulates information about the issue, including its ID, a short description, a detailed explanation, a category, and a priority level. Each issue can have associated configuration parameters, such as severity levels or additional options, to customize its behavior.</p><p>3.3 Detector: A detector is responsible for implementing the logic to identify and report issues in the codebase. It defines a set of visit methods that correspond to different AST elements, allowing you to perform checks and raise issues when certain conditions are met. The detector is registered with the lint framework, and during analysis, it is called by the visitor to inspect each element of the AST.</p><p>4. <strong>Create Method Naming Issue class</strong></p><pre>object MethodNamingIssue {<br>    /**<br>     * The fixed id of the issue<br>     */<br>    private const val ID = &quot;MethodNamingIssue&quot;<br><br>    /**<br>     * The priority, a number from 1 to 10 with 10 being most important/severe<br>     */<br>    private const val PRIORITY = 7<br><br>    /**<br>     * Description short summary (typically 5-6 words or less), typically describing<br>     * the problem rather than the fix (e.g. &quot;Missing minSdkVersion&quot;)<br>     */<br>    private const val DESCRIPTION = &quot;Wrong function name suffix.&quot;<br><br>    /**<br>     * A full explanation of the issue, with suggestions for how to fix it<br>     */<br>    private const val EXPLANATION = &quot;&quot;&quot;<br>        Function is wrongly named.<br>    &quot;&quot;&quot;<br><br>    /**<br>     * The associated category, if any @see [Category]<br>     */<br>    private val CATEGORY = Category.CUSTOM_LINT_CHECKS<br><br>    /**<br>     * The default severity of the issue<br>     */<br>    private val SEVERITY = Severity.WARNING<br><br>    val ISSUE = Issue.create(<br>        ID,<br>        DESCRIPTION,<br>        EXPLANATION,<br>        CATEGORY,<br>        PRIORITY,<br>        SEVERITY,<br>        Implementation(<br>            MethodNamingDetector::class.java,<br>            Scope.JAVA_FILE_SCOPE<br>        )<br>    )<br><br>    class MethodNamingDetector : Detector(), Detector.UastScanner {<br>        override fun getApplicableUastTypes(): List&lt;Class&lt;out UElement&gt;&gt; =<br>            listOf(UMethod::class.java)<br><br>        override fun createUastHandler(context: JavaContext): UElementHandler =<br>            MethodNamingVisitor(context)<br>    }<br>}</pre><p>5.<strong> Create Visitor class</strong></p><pre>@Suppress(&quot;UnstableApiUsage&quot;)<br>class MethodNamingVisitor(private val context: JavaContext) : UElementHandler() {<br>    override fun visitMethod(node: UMethod) {<br>        if (node.returnClassName() == &quot;String&quot;) {<br>            if (!node.name.endsWith(&quot;Once&quot;)) {<br>                reportIssue(node)<br>            }<br>        }<br>    }<br><br>    private fun UMethod.returnClassName(): String =<br>        (returnTypeReference?.type as? PsiClassType)?.className ?: &quot;&quot;<br><br>    private fun reportIssue(node: UMethod) {<br>        context.report(<br>            issue = MethodNamingIssue.ISSUE,<br>            scopeClass = node,<br>            location = context.getNameLocation(node),<br>            message = &quot;&quot;&quot;<br>                [String] string parameters must have a Once key at the end.<br>                Example: removeAccountOnce()<br>            &quot;&quot;&quot;<br>        )<br>    }<br>}</pre><p>6.<strong> Now we need register our custom lints for this we create Registry class</strong></p><pre>@Suppress(&quot;UnstableApiUsage&quot;)<br>class CustomLintRegistry : IssueRegistry() {<br>    override val issues =<br>        listOf(<br>            MethodNamingIssue.ISSUE<br>        )<br><br>    override val api: Int = CURRENT_API<br><br>    override val minApi: Int = 6<br>}</pre><p>7. <strong>Add this line in lint-rule’s build.gradle (Don’t forget to change direction)</strong></p><pre>jar {<br>    manifest {<br>        attributes(&#39;Lint-Registry-v2&#39;: &#39;az.khayalsharifli.lint_rules.CustomLintRegistry&#39;)<br>    }<br>}</pre><p>8. <strong>Add lint-rules module in our main module</strong></p><pre>dependencies {<br>    implementation fileTree(dir: &#39;libs&#39;, include: [&#39;*.jar&#39;])<br>    // Lint module<br>    lintChecks project(&#39;:lint-rules&#39;)<br>}</pre><p><strong>9. Now only write “./gradlew lint” in Android Studio terminal</strong></p><p>10. <strong>And this is our custom lint worked</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlMs8EepGGMFsha0HupUyA.png" /></figure><p>Finally, I hope this was helpful for you, you can view all the code by linking to my <a href="https://github.com/khayalsherif/custom-rules">Github Repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf6df7045fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstraction in Kotlin]]></title>
            <link>https://khayalsharifli.medium.com/abstraction-in-kotlin-6ad4e90842d3?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad4e90842d3</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 08:13:41 GMT</pubDate>
            <atom:updated>2023-03-21T08:13:41.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPdRYUFU_n1L7BJPp-EhHw.png" /></figure><ol><li>What is Abstraction?</li><li>How use Abstraction in Kotlin?</li><li>When use Abstraction class?</li><li>When use Interface?</li><li>What is a main different Abstract class and Interface?</li></ol><h4>What is Abstraction?</h4><p>Abstraction is one of the main principles of the Kotlin programming language and is present in many languages. The main purpose of abstraction is to make the code more readable and understandable. By hiding details about an object’s internal functionality, it makes the code cleaner and easier to install.</p><h4>How use Abstraction in Kotlin?</h4><p>We have two ways for use abstraction: Abstract class and Interface, but they have some differences in their usage. Interfaces define a set of abstract methods that must be implemented by the classes that implement the interface. In other words, interfaces define what a class can do, not how it does it.</p><h4>When use Abstraction class?</h4><p>Abstract classes are used when you want to provide a common implementation for a group of related classes. For example Base classes (BaseFragment, BaseViewModel and so). You can define abstract properties, methods, and functions in an abstract class, which are not implemented in the abstract class itself, but must be implemented in the subclass that inherits from it. Abstract classes can also have non-abstract methods with default implementations.</p><h4>When use Interface?</h4><p>Interfaces are used when you want to define a contract that classes can implement. Interfaces are useful for creating loosely-coupled code, as they allow you to define a contract between components without specifying their implementation.</p><h4>What is a main different Abstract class and Interface?</h4><p>Although there are many differences between them, today we will talk about what I think is the most important difference. This different is a about state. Abstract class can contain state but interface can not contain state. Interfaces only can contain property and abstract functions. We can not create variable in interface but can this in abstract classes.</p><p>Sometimes in interviews, when talking about the differences between abstract classes and interfaces, a question is asked that will confuse us.</p><p>Let’s look at the code below:</p><pre>interface Test {<br>    val string: String<br>        get() = &quot;String for test&quot;<br>}</pre><p>If we cannot create a variable (containing state) in an interface, then how did we manage to write with ‘val’ or ‘var’ the above code. The answer is very simple in this ‘string’ is not variable it is a property function.</p><p>Let’s look at this code to understand more clearly:</p><pre>interface Test {<br>    fun string(): String {<br>        return &quot;String for test&quot;<br>    }<br>}</pre><p>This code is the same as the code we wrote earlier and there is no difference between them. When we write get(), it actually creates a function for us that returns a String value and sets it to ‘string’.</p><p>Finally, I hope this was helpful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad4e90842d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency injection with Koin]]></title>
            <link>https://khayalsharifli.medium.com/dependency-injection-with-koin-46a0a8a6ecba?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a0a8a6ecba</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 09:46:12 GMT</pubDate>
            <atom:updated>2023-02-14T09:47:09.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8qV4pmDTJQPkSowg1BS6A.jpeg" /></figure><ol><li>What is Koin and which are characteristics?</li><li>How implementation Koin?</li><li>What is main concepts in Koin?</li><li>How we use Koin?</li><li>Scoping with Koin.</li><li>Lazy object in Koin.</li></ol><h4>What is koin and which are characteristics ?</h4><p>Koin is dependency injection library which is pure kotlin. It provides dependencies at the runtime. And it work with modules which are created with the application start. Koin characteristics:</p><ol><li>Well suited for Kotlin.</li><li>Koin is a fast at the compile time but slower at the runtime.</li><li>Support Kotlin Multiplatform.</li><li>Coding and reading is a easier with koin. (just my opinion)</li></ol><h4>How implementation koin?</h4><p>First of all, we implementation koin library in build.gradle files.</p><pre>dependencies {<br>    // Koin for Kotlin apps<br>    implementation &quot;io.insert-koin:koin-core:$koin_version&quot;<br>    // Koin for Android<br>    implementation &quot;io.insert-koin:koin-android:$koin_android_version&quot;<br>    // Koin for ViewModel<br>    implementation &quot;io.insert-koin:koin-androidx-viewmodel:$koin_android_version&quot;<br>    // Java Compatibility<br>    implementation &quot;io.insert-koin:koin-android-compat:$koin_android_version&quot;<br>    // Jetpack WorkManager<br>    implementation &quot;io.insert-koin:koin-androidx-workmanager:$koin_android_version&quot;<br>    // Navigation Graph<br>    implementation &quot;io.insert-koin:koin-androidx-navigation:$koin_android_version&quot;<br>    // Jetpack Compose<br>    implementation &quot;io.insert-koin:koin-androidx-compose:$koin_android_version&quot;<br>}</pre><h4>What is a main concepts in Koin?</h4><p><strong>Module</strong> - It is a object type which is provide all the dependencies.</p><p><strong>Single</strong> - It creates a singleton that can be used across the app as a singular instance.</p><p><strong>Factory</strong> - It will create new instance each time it is injected</p><p><strong>get()</strong> - It use to get injection objects.</p><h4>How we use koin?</h4><ol><li>First we create module object for injection objects we do this with the module{}.</li></ol><pre>val dataModule = module{<br>/** LocalDataSource is a interface and LocalDataSourceImpl is a class<br> which is a override LocalDataSource functions.**/<br>    single&lt;LocalDataSource&gt; {<br>        LocalDataSourceImpl(dao = get())<br>    }<br>}</pre><p>2. Second we load modules in the Application class with startKoin{}.</p><pre>class App : Application() {<br>    // Don&#39;t forget to declare your Application object in the Manifest!<br>    override fun onCreate() {<br>        super.onCreate()<br>        startKoin {<br>            /** If you have a multiple modules then will create <br>                a module object list and pass the modules function<br>            **/<br>            val modules = listOf(dataModule,and so...)<br>            modules(modules)<br>        }<br>    }<br>}</pre><p><strong>Scoping in koin</strong></p><p>You can create limit a lifetime of your injected with scoping. For this we create other module:</p><pre>val scopingModule = module {<br>    // If you have of the same type objects but they contain different value we use named()<br>    scope&lt;MainActivity&gt; {<br>        scoped(qualifier = named(&quot;hello&quot;)) { &quot;Hello Word&quot; }<br>        scoped(qualifier = named(&quot;bye&quot;)) { &quot;Bye&quot; }<br>    }<br>}</pre><p>And we for use this in the MainActivity, implementation AndroidScopeComponent interface (doesn’t work in Compose) in the MainActivity(We can do this for every sing scope for example: Service,Fragment, and so..) and use this injection object :</p><pre>class MainActivity : AppCompatActivity(), AndroidScopeComponent {<br><br>    override val scope: Scope by activityScope()<br>    private val hello by inject&lt;String&gt; (named(&quot;hello&quot;))<br>    private val bye by inject&lt;String&gt; (named(&quot;bye&quot;))<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent(R.id.layout_main)<br>        Log.e(&quot;This is our hello injection object&quot;, hello)<br>        Log.e(&quot;This is our bye injection object&quot;, bye)<br>    }<br>}</pre><p><strong>Lazy object in koin</strong></p><ul><li>You can do a field injection like this to achieve instant injection:</li></ul><pre>private val localDataSource = get&lt;LocalDataSource&gt;()</pre><ul><li>With lazy injection (prefer this):</li></ul><pre>private val localDataSource by inject&lt;LocalDataSource&gt;()</pre><p><strong>Bonus :</strong></p><p><strong>Property - </strong>is the logic which is a work key value. We pass value with<strong> </strong>properties() function in the Application class:</p><pre>class App : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        startKoin {<br>            properties(<br>                mapOf(&quot;base_url&quot; to &quot;Our base url&quot;)<br>            )<br>            val moduleList = listOf(dataModule, and so ...)<br>            modules(moduleList)<br>        }<br>    }<br>}</pre><p>And for get our value we use <strong>getProperty():</strong></p><pre>val dataModule = module {<br>    single {<br>        Retrofit.Builder()<br>            .baseUrl(getProperty&lt;String&gt;(&quot;base_url&quot;))<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .client(get())<br>            .build()<br>    }<br>}</pre><p>Finally, I hope this was helpful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a0a8a6ecba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Android for Clean Architecture .]]></title>
            <link>https://khayalsharifli.medium.com/testing-in-android-for-clean-architecture-4983699f773a?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4983699f773a</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[android-cleanarchitecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 06:57:11 GMT</pubDate>
            <atom:updated>2022-11-11T06:57:11.433Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing in Android for Clean Architecture .</h3><p>What is testing in Android and how can we write tests for a clean architecture?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsJLAmQi_ipHk9T8VrqNfQ.jpeg" /></figure><h4>- Introduction and Overview</h4><p>Tests are a tool that lets us know if your app’s functionality is working properly. There are two kinds testing - test(Local Test) and androidTest(Instrumented Test). Local test is approach to run unit tests that have no dependencies on the Android framework or have dependencies that mock objects can satisfy. Instrumented test is one that uses the Android component(Fragment, Activity, and so). Instrumented test use android emulator, therefore Instrumented testing is run later than Local testing. In this article I will talk about how we can write test for clean architecture and we will use <a href="https://github.com/khayalsherif/nasa">nasa project</a>. This is my project and I wrote to talk about the test.</p><ol><li><strong>Data testing</strong></li><li><strong>Domain testing</strong></li><li><strong>Presentation testing</strong></li></ol><p>You can get all the used libraries from within the <a href="https://github.com/khayalsherif/nasa">nasa app</a>. Before starting the article, I want to talk about the logic we use when writing tests, because we will use it all the time. Thus, we generally break tests down into three main sections: given, when, and then.</p><ol><li>GIVEN: Set up condition</li><li>WHEN: Action is taken</li><li>THEN: An assertion is true</li></ol><p>Okay If we know that, we can start</p><p><strong>Data</strong></p><p>1.1 Mapper testing in (Local test)</p><pre>class EpicMapperTest {<br><br>    private lateinit var epicMapper: EpicMapper<br><br>    @Before<br>    fun setUp() {<br>        epicMapper = EpicMapper()<br>    }<br><br>    @Test<br>    fun remoteToLocalTest() {<br>        //Given<br>        val remote = EpicFactory.generateRemoteEpic()<br><br>        //When<br>        val local = epicMapper.remoteToLocal(remote)<br><br>        //Then<br>        assertRemoteToLocalTest(remote, local)<br>    }<br><br>    <em>/**<br>     * Helper Methods<br>     **/<br>    </em>private fun assertRemoteToLocalTest(remote: EpicRemoteDto, local: EpicLocalDto) {<br>        val remoteCoordinatesLat = remote.centroid_coordinates.lat<br>        val remoteCoordinatesLon = remote.centroid_coordinates.lon<br>        val localCoordinatesLat = local.centroid_coordinates.lat<br>        val localCoordinatesLon = local.centroid_coordinates.lon<br><br>        Truth.assertThat(remote.caption).isEqualTo(local.caption)<br>        Truth.assertThat(remote.date).isEqualTo(local.date)<br>        Truth.assertThat(remote.identifier).isEqualTo(local.identifier)<br>        Truth.assertThat(remote.version).isEqualTo(local.version)<br>        Truth.assertThat(remote.image).isEqualTo( local.image)<br>        Truth.assertThat(remoteCoordinatesLat.toString()).isEqualTo( localCoordinatesLat.toString())<br>        Truth.assertThat(remoteCoordinatesLon.toString()).isEqualTo(localCoordinatesLon.toString())<br>    }<br>}</pre><p>In the code snippet above, we first create a lateinit variable called epicMapper, we set a value to epicMapper in setUp() function and we do with @Before annotation. Before each test function, the function we declared <a href="http://twitter.com/Before">@Before</a> will be called. Next steps we write testing function with @Test annotation. First, we get remote data from the factory object (it is fake data generator). Second, we convert the remote model to the local model with the epicMapper variable. And finally, we check the remote and local model with our helper method. In the helper method, we used the Truth library and checked that the remote data is equal to the local data by calling assertThat(“String”).isEqualTo(“String”). If each assertThat() method returns true, the assertRemoteToLocalTest() function will return true. It’s that simple</p><p>1.2 Repository testing (Local test)</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class EpicRepositoryTest {<br><br>    @Mock<br>    lateinit var mapper: EpicMapper<br><br>    @Mock<br>    lateinit var service: EpicService<br><br>    @Mock<br>    lateinit var epicLocalDataSource: EpicLocalDataSource<br><br>    private lateinit var epicRepository: EpicRepositoryImpl<br><br>    @Before<br>    fun setUp() {<br>        epicRepository = EpicRepositoryImpl(<br>            mapper = mapper,<br>            epicService = service,<br>            epicLocalDataSource = epicLocalDataSource<br>        )<br>    }<strong><br> <br>    </strong>@Test<br>    fun `get data from remote data source`() = <em>runBlocking </em><strong>{<br>        </strong>//Given<br>        val remoteDtoList = EpicFactory.generateRemoteEpicList(4)<br><br>        //When<br>        stubServiceGetEpics(remoteDtoList)<br><br>        //Then<br>        Truth.assertThat(<br>            service.getEpics()<br>        ).isEqualTo(remoteDtoList)<br>    <strong>}<br></strong><br>    private fun stubServiceGetEpics(epicRemoteList: List&lt;EpicRemoteDto&gt;) = <em>runBlocking </em><strong>{<br>        </strong>Mockito.`when`(service.getEpics())<br>            .thenReturn(epicRemoteList)<br>    <strong>}<br><br></strong>}</pre><p>In this test class, we first used the <a href="http://twitter.com/RunWith">@RunWith</a>(MockitoJUnitRunner::class) annotation because we will be using the <a href="https://site.mockito.org/">Mockito</a> library. First, we’ll create the lateinit variables with @Mock annotation that we’ll use as arguments to EpicRepositoryImpl(). In the next step, we create the stubServiceGetEpics() function and write what will be returned when we call service.getEpics() The returned data is our mock data and we get this data from the function constructor. The remaining parts are as I explained in the mapper testing.</p><p>1.3 Local data base testing (Instrumented test)</p><pre>@RunWith(AndroidJUnit4::class)<br>@ExperimentalCoroutinesApi<br>class EpicDaoTest {</pre><pre>    private lateinit var dataBase: EpicDataBase<br>    private lateinit var epicDao: EpicDao<br><br>    @get:Rule<br>    var rule = InstantTaskExecutorRule()<br><br>    @Before<br>    fun setup() {<br>        //inMemoryDatabaseBuilder - is create database in device ram<br>        dataBase = Room.inMemoryDatabaseBuilder(<br>            ApplicationProvider.getApplicationContext(),<br>            EpicDataBase::class.<em>java<br>        </em>).allowMainThreadQueries().build()<br>        epicDao = dataBase.epicDao()<br>    }<br><br>    @After<br>    fun tearDown() {<br>        dataBase.close()<br>    }<br><br>    @Test<br>    fun insertEpic() = <em>runBlocking </em><strong>{<br>        </strong>//Given<br>        val epicItem = DataFactory.generateLocalDto()<br>        <br>        //When<br>        epicDao.insertEpic(<em>listOf</em>(epicItem))<br><br>        //Then<br>        val allEpicItem = ArrayList&lt;EpicLocalDto&gt;()<br>        epicDao.observeEpic().test <strong>{<br>            </strong>val list = this.awaitItem()<br>            for (i in list) allEpicItem.add(i)<br>        <strong>}<br>        </strong>assertThat(allEpicItem).isEqualTo(<em>listOf</em>(epicItem))<br>    <strong>}<br><br></strong>}</pre><p>This test is different from other tests because it is a instrumented test and we will be using Android Emulator. This’s why we use @RunWith(AndroidJUnit4::class) annotation and we will use kotlin coroutine functions, so we use <a href="http://twitter.com/ExperimentalCoroutin">@ExperimentalCoroutin</a>esApi annotation.In this we testing persistent storage (Room). Before we create room database in device ram because we use device ram when writing tests because tests are transient and it makes no sense to do it in main memory. This is the topic that we should focus on in this part. Everything else is the same</p><p><strong>Domain</strong></p><p>2.1 Use Case testing (Local testing)</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class EpicObserveUseCaseTest {<br><br>    @Mock<br>    lateinit var context: CoroutineContext<br><br>    @Mock<br>    lateinit var convertor: ErrorConverter<br><br>    @Mock<br>    lateinit var repository: EpicRepository<br><br>    private lateinit var epicObserveUseCase: EpicObserveUseCase<br><br>    @Before<br>    fun setUp() {<br>        epicObserveUseCase =<br>            EpicObserveUseCase(context, convertor, repository)<br>    }<br><br>    @Test<br>    fun `observe data from repository`() = <em>runBlocking </em><strong>{<br>        </strong>//Given<br>        val epicDomainList = EpicFactory.generateDomainEpicList(4)<br>        val flow = <em>flow </em><strong>{ </strong>emit(epicDomainList) <strong>}<br><br>        </strong>//When<br>        stubRepositoryObserveEpic(flow)<br><br>        //Then<br>        Truth.assertThat(repository.observeEpics()).isEqualTo(flow)<br>    <strong>}<br><br>    </strong>private fun stubRepositoryObserveEpic(flow: Flow&lt;List&lt;Epic&gt;&gt;) {<br>        `when`(repository.observeEpics())<br>            .thenReturn(flow)<br>    }<br>}</pre><p>İn UseCase testing looks like other testing. As I said before, if you understand the logic, you will write easy test code. With this we focus on flow testing, we just check with the Truth library as normal data.</p><p><strong>Presentation</strong></p><p>3.1 View Model testing (Local testing)</p><pre>@RunWith(MockitoJUnitRunner::class)<br>class HomeViewModelTest {<br><br>    @OptIn(ExperimentalCoroutinesApi::class)<br>    @get:Rule<br>    var mainCoroutineRule = MainCoroutineRule()<br><br>    @Mock<br>    private lateinit var homeViewModel: HomeViewModel<br><br>    @Test<br>    fun `observe epicResponse data `() = <em>runBlocking </em><strong>{<br>        </strong>//Given<br>        val epicDomainList = EpicFactory.generateDomainEpicList(4)<br>        val stateFlow = <em>MutableStateFlow</em>(epicDomainList).<em>asStateFlow</em>()<br><br>        //When<br>        stubHomeViewModelEpicResponse(stateFlow)<br><br>        //Then<br>        Truth.assertThat(homeViewModel.epicResponse.first())<br>            .isEqualTo(stateFlow.first())<br>    <strong>}<br><br>    </strong>@Test<br>    fun `observe empty epicResponse data `() = <em>runBlocking </em><strong>{<br>        </strong>//Given<br>        val epicDomainList = EpicFactory.generateDomainEpicList(0)<br>        val stateFlow = <em>MutableStateFlow</em>(epicDomainList).<em>asStateFlow</em>()<br><br>        //When<br>        stubHomeViewModelEpicResponse(stateFlow)<br><br>        //Then<br>        Truth.assertThat(homeViewModel.epicResponse.first())<br>            .isEqualTo(stateFlow.first())<br>    <strong>}<br><br>    </strong>private fun stubHomeViewModelEpicResponse(flow: StateFlow&lt;List&lt;Epic&gt;&gt;) {<br>        Mockito.`when`(homeViewModel.epicResponse).thenReturn(flow)<br>    }<br>}</pre><p>I hope this information is helpful to you. If you have any queries or feedback please write back. Always happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4983699f773a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Constraint Layout]]></title>
            <link>https://medium.com/abb-innovation/constraint-layout-b7943620d29c?source=rss-27e900aa10e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7943620d29c</guid>
            <category><![CDATA[constraintlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[baseline]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[chain]]></category>
            <dc:creator><![CDATA[Khayal Sharifli]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 12:28:00 GMT</pubDate>
            <atom:updated>2024-02-26T12:49:50.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GaTQcic9rVWD22NeEXBRQ.jpeg" /></figure><p>A <strong>ConstraintLayout </strong>is a ViewGroup which allows you to Position and size Views in a flexible way. The Views will be positioned and sized w.r.t other Views with the Use of Constraints.</p><p>This article is intended for those who have knowledge of <strong>constraint layout</strong> and want to learn <strong>detailed</strong>. Looking at the general sub-themes first, they are as follows.</p><ul><li><strong>Baseline Alignment</strong></li><li><strong>Guideline</strong></li><li><strong>Barriers</strong></li><li><strong>Ration</strong></li><li><strong>Group</strong></li><li><strong>Chains</strong></li></ul><p><strong>What is Baseline Alignment ?</strong></p><p>Baseline refers to views that contain text. Used to align the text baseline of a view with the text baseline of another view. The order of use is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*cnCPlbm5-Anx5xIAi6e2oQ.gif" /></figure><p><strong>What is Guideline ?</strong></p><p>A guideline (vertical or horizontal) is used to constrain views. Invisible to the user, guidelines are visible only to the developer. The order of use is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GeGSz_AepUjkqNxmAHwdKw.gif" /></figure><p><strong>What is Barriers?</strong></p><p>Similar to a guideline, a barrier is an invisible line that you can constrain views to. Except a barrier does not define its own position; instead, the barrier position moves based on the position of views contained within it. This is useful when you want to constrain a view to the a set of views rather than to one specific view.</p><ul><li><em>For example, C is constrained to the right side of a barrier. The barrier is set to the “end” (or the right side in a left-to-right layout) of both view A and view B. So the barrier moves depending on whether the right side of view A or view B is is farthest right.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-kTMrePAC5CwAcPsdUKNw.png" /></figure><p>The order of use is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VtZd9IyUexAHLvo06tHnjw.gif" /></figure><p><strong>What is Ration ?</strong></p><p>Using this layout constraint, we can define one dimension (Height or Width) of a View as a ratio of another dimension. Actually this function is very good because we just set the ratio we want inside the xml without using any Java or Kotlin code for it.</p><p>Suppose you have width to ScreenWidth and Image Aspect Ratio should be 16:9, then layout_constraintDimensionRatio will be useful to fulfill above requirement. The following code will demonstrate how to use this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eitV8uh-codLq-mwZJ5ohw.png" /></figure><p><strong>What is Group?</strong></p><p>If you schedule an appointment within the same group, you can perform the same action on all appointments at the same time. This will save you from long codes.</p><ul><li><em>For example We have two different textViews and every time we want to make them both invisible we “</em><strong>android:visibility= gone”</strong> <em>them separately, instead it would be better to set them inside a group and give the group this code,</em>Like the example below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXRi-oguHXGRAtOIC5MJoQ.png" /></figure><p><strong>What is Chains?</strong></p><p>A chain is a group of interconnected views with bidirectional constraints.</p><ol><li><strong>Spread:</strong> The views are evenly distributed (after margins are accounted for). This is the default.</li><li><strong>Spread inside:</strong> The first and last view are affixed to the constraints on each end of the chain and the rest are evenly distributed.</li><li><strong>Packed:</strong> The views are packed together (after margins are accounted for). You can then adjust the whole chain’s bias (left/right or up/down) by changing the chain’s head view bias.</li><li><strong>Weighted: </strong>The views are distributed according to the weights set on the screen</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Ux_qcJM1YuoI8MvbeRBmHw.png" /></figure><p>The order of use is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ntuhJ13gMBXDVw1CHs45Ug.gif" /></figure><p>I hope this information is helpful to you. If you have any queries or feedback please write back. Always happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7943620d29c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/abb-innovation/constraint-layout-b7943620d29c">Advanced Constraint Layout</a> was originally published in <a href="https://medium.com/abb-innovation">ABB Innovation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>