<?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 Kelvin Watson on Medium]]></title>
        <description><![CDATA[Stories by Kelvin Watson on Medium]]></description>
        <link>https://medium.com/@kelvinwatson?source=rss-55165c04ec5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QvchiiuYisX250JE66CpeA.jpeg</url>
            <title>Stories by Kelvin Watson on Medium</title>
            <link>https://medium.com/@kelvinwatson?source=rss-55165c04ec5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:15:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kelvinwatson/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[Bodybuilding recipes: Peanut sauce]]></title>
            <link>https://kelvinwatson.medium.com/bodybuilding-recipes-peanut-sauce-22e8a473d380?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e8a473d380</guid>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 03:10:50 GMT</pubDate>
            <atom:updated>2024-09-20T03:19:20.859Z</atom:updated>
            <content:encoded><![CDATA[<p>Non-fat greek or plain yogurt is a great base for making all sorts of sauces during contest prep. Peanut powder is another great substitute for peanut butter. Not only can it be reconsituted with water to create an awesome tasting peanut butter, it is extremely versatile and can be used in smoothies and sauces.</p><p>Peanut sauce is a tasty fixture in so many Asian dishes. Growing up, I used to love peanut sauce with Vietnamese salad rolls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UynDLuItVsyXEij-" /></figure><h3>Ingredients</h3><ul><li>4 tbsp non-fat greek or plain yogurt</li><li>22.5 to 30g peanut powder</li><li>1 tbsp soy sauce</li><li>1 tsp allulose, monk fruit, Splenda, stevia, or other zero-calorie sweetener</li><li>(optional) pinch of ginger powder</li><li>(optional) 1/4 tsp sweet chili sauce (sugar free if possible)</li><li>(optional) 1/4 tsp rice vinegar</li></ul><h3>Instructions</h3><ol><li>Mix all ingredients in a small bowl</li><li>Serve with your favorite meals</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e8a473d380" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bodybuilding recipes: Cottage cheese oatmeal cookies]]></title>
            <link>https://kelvinwatson.medium.com/bodybuilding-recipes-cottage-cheese-oatmeal-cookies-4b6dba6ed1e3?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6dba6ed1e3</guid>
            <category><![CDATA[protein]]></category>
            <category><![CDATA[bodybuilding]]></category>
            <category><![CDATA[oatmeal-cookie]]></category>
            <category><![CDATA[low-fat]]></category>
            <category><![CDATA[low-carb]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 03:51:14 GMT</pubDate>
            <atom:updated>2024-09-03T04:17:45.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3_sASq_bPdg-XJHg" /></figure><p>It’s pretty easy to find recipes that make high-protein baked goods. However, what the recipes often won’t emphasize is the fat content. It’s hard to find recipes that are non-fat or very low fat.</p><p>As I train for my first bodybuilding show in October, I’m finding the cravings for baked goods is getting stronger and stronger as my diet is being optimized. I find myself wandering around the bakery department in grocery stores wondering if there’s anything at all that I can eat. Of course there isn’t; everything is either full of sugar or fat. Some baked goods—especially those prepared in store—don’t even have macros listed. In either of those cases, I can’t eat them.</p><p>I’m not a cook, but I decided I needed to figure out how I can satisfy these cravings in a bodybuilding show-preparatory safe way. Enter cottage cheese oatmeal cookies!</p><p>They’re based off a 2-ingredient oatmeal cookie recipe I found all over the internet. One part apple sauce to two parts quick oats. This recipe is my variation, with a boost of protein. Best of all, it’s very low in fat. They take no time to make, and can be air fried or baked. You can have them with your coffee as part of a pre-workout meal to give you that carb-filled energy boost. They’re a tasty alternative to a banana or oatmeal.</p><p>I substituted pumpkin and non-fat cottage cheese for applesauce. I also replaced some of the oats with protein powder, which effectively makes it a 4 ingredient oatmeal cookie. There are a ton of other optional ingredients you can add to give it amazing flavor, which I’ll list below. The “recommended” ingredients are mostly for additional protein and flavor. I highly recommend adding the cardamom and pumpkin pie spices for a truly unique flavor.</p><p>I decided on pumpkin because it has a better carb profile than unsweetened applesauce per serving and has a tiny bit of protein. Applesauce has more sugar and no protein content. Cottage cheese is really having a moment right now, being featured into a plethora of recipes lately. Non-fat cottage cheese is an excellent protein source with no fat! I personally don’t love the taste of cottage cheese eaten as is, so cooking with it has made it much more palatable and easy to incorporate into my diet. It gives the oatmeal cookies a hint of a baked cream cheese-like flavor, which I actually love, and I hope you do too.</p><h3>Approximate macronutrient profile</h3><p>Per 25g cookie:</p><ul><li>Calories: 40</li><li>Fat: 0.45g</li><li>Carbs: 5.45g</li><li>Protein: 3.25g</li></ul><h3>Ingredients</h3><ul><li>Oil spray for parchment paper</li><li><strong>200g of quick oats</strong></li><li><strong>400g of pumpkin </strong>(or unsweetened applesauce)</li><li><strong>113g of non-fat cottage cheese</strong> (or any % fat if you’re not in show prep)</li><li><strong>50g whey protein powder</strong></li><li>(Recommended) 3 tbsp pumpkin pie spice and/or 3 pumps of sugar free pumpkin syrup</li><li>(Recommended) 1/4 tbsp cardamom</li><li>(Recommended) 2 tbsp vanilla, vanilla extract or vanilla blend</li><li>(Recommended) 1 or 2 servings of peanut powder or almond powder</li><li>(Recommended) 2/3 cup Stevia (or other sweetener)</li><li>(Recommended) 1/4 or 1/3 cup golden allulose sweetener</li><li>(Optional) 1 serving of collagen protein powder</li><li>(Optional) 1 tbsp sugar-free chocolate chips</li><li>(Optional) 1 tbsp baking powder</li></ul><h3>Instructions</h3><ol><li>Preheat oven or air fryer to 350 degrees</li><li>Place parchment paper on a cookie sheet</li><li>Spray cookie sheet with a small amount of oil</li><li>Optional — Blend cottage cheese until smooth</li><li>Mix all ingredients in a large bowl</li><li>Scoop onto a baking sheet using a cookie scoop</li><li>Air fry or bake for 13 minutes</li><li>Drizzle with sugar-free chocolate syrup if desired</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6dba6ed1e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bodybuilding recipes: Protein “ice cream” pucks]]></title>
            <link>https://kelvinwatson.medium.com/bodybuilding-recipes-protein-ice-cream-pucks-58ac79948c4e?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ac79948c4e</guid>
            <category><![CDATA[diet]]></category>
            <category><![CDATA[protein]]></category>
            <category><![CDATA[bodybuilding]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[bodybuilding-diet]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 05:26:39 GMT</pubDate>
            <atom:updated>2024-08-31T05:35:44.738Z</atom:updated>
            <content:encoded><![CDATA[<p>Bodybuilding recipes: Protein “ice cream” pucks</p><p>Much of bodybuilding is diet. The saying goes, “75% of your results come from the kitchen”. Training is easy, dieting is hard.</p><p>Thankfully, there are so many ways to hack your way through your bodybuilding diet. When I say “hack”, I don’t mean “cheat”. You can still have great tasting food without sacrificing your health. Similarly, you can build lean muscle, but still enjoy tasty dishes at the same time.</p><p>Today, we’re making an ice cold sweet treat that will satisfy your cravings for ice cream. Best of all, it’s high in protein, non-fat and low in carbs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ll-ouIjb00QpNBHd8P1geQ.jpeg" /><figcaption>High-protein low-carb non-fat “ice cream” pucks</figcaption></figure><h3><strong>Protein “ice cream” pucks</strong></h3><p>Approximate macro profile</p><p>Per 50g serving:</p><ul><li>Calories: 59</li><li>Fat: 0.75g</li><li>Carbs: 3.9g</li><li>Protein: 9.7g</li></ul><h4>Ingredients</h4><ul><li>350g plain non-fat yogurt (or non-fat greek yogurt)</li><li>30g peanut powder or almond butter powder</li><li>3 tbsp <strong>sugar-free</strong> syrup (flavored or non-flavored)</li><li>1/4 cup allulose/monk fruit brown sugar sweetener (or any other zero calorie sweetener)</li><li>3 tbsp cocoa powder (optional)</li><li>2 scoops of collagen powder</li><li>1 scoop of egg white powder, non-fat milk powder, protein powder</li></ul><h4>Cooking instructions</h4><ol><li>Mix all ingredients in a large bowl</li><li>Place parchment paper onto a baking sheet or any large freezer-safe dish or tray.</li><li>Using a cookie scoop, scoop onto parchment paper</li><li>Place pucks into the freezer until thoroughly frozen (at least 1 hour)</li><li>Enjoy!</li></ol><p>Variations and tips</p><ul><li>You can improve the protein profile drastically by adding more egg white powder, non-fat milk powder or protein powder</li><li>Removing the cocoa powder from the recipe will drop the carbohydrate content in half</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ac79948c4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My phone was stolen in Spain. Things I learned]]></title>
            <link>https://kelvinwatson.medium.com/my-phone-was-stolen-in-spain-things-i-learned-7615701d0d4f?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7615701d0d4f</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[identity-theft]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 07:41:44 GMT</pubDate>
            <atom:updated>2024-07-28T18:20:07.643Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Without access to my home country’s phone number or another trusted device, I could not two-factor into my Google account, effectively locking myself out of my own accounts.</blockquote><p>On my second day of my three-week solo trip in Europe, my phone was stolen. I was drugged and without my phone in the middle of a foreign country. It was 3:30am in the morning. I was on the streets, lost, and hoped that I would wake up from this nightmare.</p><p>Our phones have become the center of everything in our lives. However, this reliance can become a vulnerability when our devices are lost or stolen. In this era of mobile devices, with unfettered internet access and cloud storage, many of us no longer remember phone numbers or addresses. However, doing so can be crucial for recovering your accounts, sanity, and most importantly, your identity.</p><p>Fortunately, I managed to remember the address where I was staying and my brother’s phone number. Had I not been able to recall these data points from memory, I would have had to find my way to the police station that night. Even then, I would still have to remember someone’s phone number or an email address.</p><p>Without a second device with me, I was completely “blind” for days with respect to my trip tickets, itinerary, and numerous reservations. Meanwhile, the thieves were already making purchases with my digital wallet and deleting photos to cover their tracks.</p><p>I did not sleep for at least 30 hours after returning back to my host’s condo. Thankfully, he had a spare device I could use. It wasn’t of much help, but it was something. He let me use his Facebook account to comment on a loved one’s public post to signal that I needed help.</p><p>Losing my phone was one thing, but losing access to my email and cloud storage meant I was unable to retrieve important details about my trip. Train tickets, event reservations, boarding passes, and other critical items I needed for my time in Europe, were inaccessible. Thankfully, I had prepared a Google document with all of my trip details, dates, and reservation/confirmation numbers, and shared this document with two of my family members. These helped to recover some of my reservations, but not all of them.</p><p>I didn’t have time to process the fact that my privacy was thoroughly violated. All of my emails, contacts, and personal data completely invaded and exposed. I needed to act fast, get a replacement phone and begin locking down my accounts, financial, socials, and anything else I could remember.</p><p>Over the course of the next two days, I spent hours dealing with my home country phone carrier. I needed to freeze or temporarily cancel my phone number so that the thieves could not use it to two-factor into my accounts. However, the carrier required my IMEI number and three phone numbers I contacted the most. Being only able to provide two of those phone numbers was insufficient to access my account to perform security measures to protect myself. In essence, I was unable to prove I was, in fact, me. The MVNO carrier I dealt with only had an online support track. You may have better luck if you’re able to contact a carrier company that offers in-person or phone support.</p><p>Side note: Your phone’s serial number is required for filing police reports in Spain. The police station will turn you away if you don’t have this information.</p><p>Without access to my home mobile phone number, I could not two-factor into my Google account, effectively locking myself out of many other accounts. I was able to obtain a SIM card while in Spain, but as a tourist, there was only one plan I could purchase. Purchasing that SIM card required a passport, which I happened to have with me at the time. Keep that in mind when trying to obtain a SIM card at wireless carrier physical stores. While this tourist/visitor phone plan provided ample data, it only allowed me to make local calls. Yes, you read that right: I could not make calls to 1–800 numbers. It also offered no SMS.</p><p>To reach my financial institutions, I needed my friend to call the institution, then loop me in a three way call. I was able to lock down my accounts this way, but it took additional time and effort. The longer this was delayed, the more damage the thieves were able to do. Keep in mind though, that locking down an account or disputing transactions could mean that you would have to cancel that payment card. In that case, you should ensure that you have at least one other spare payment method as a backup while traveling. Do not add all of your payment methods to our digital wallet in case your phone is compromised, as was the case with me. Fortunately, I had one spare card that wasn’t part of my digital wallet that I was able to use for the remainder of my trip.</p><p>If your photos are important to you, consider keeping copies in a second account that isn’t tied to your main account. This applies to contacts as well.</p><p>If thieves have access to your main account—in my case, they did—they could access your emails, important files, identification details, wipe photos, or worse, completely lock you out of your accounts by changing your passwords.</p><p>In my case, Google was able to block their numerous attempts to change my passwords. If your password is easy to guess from hints left in emails or cloud storage, you could risk a breach to your accounts and lose them forever. Hence, consider backing up photos and other important documents in an account that’s separate from your main account.</p><p>I’ve compiled a list of things I would have done differently to better prepare for my trip. Having gone through this experience, I have a new found awareness of, and appreciation for, how vulnerable we are and how much we truly rely on technology to be “safe”. We often think that this “couldn’t possibly happen to me”. I would venture to guess that many—if not most—of us store confidential and deeply personal data in our emails and cloud storage. Perhaps we’ve applied for a mortgage and needed to email details to brokers, insurance companies, banks, Escrow intimate financial details, social security numbers and the like. Now, imagine all of that data in the wrong hands.</p><p>On the flip side, while we trust technology to keep us safe, sometimes they can overreach and make it difficult to prove you are, well, you.</p><h3>Before traveling:</h3><ul><li>Bring a second device with you. This could be a second phone, a tablet, or a laptop. This device should be a “trusted” device that can either allow or temporarily bypass two factor authentication into your Google account (or your login method of choice). In a foreign country, you will likely not be able to use your home country’s phone number for 2FA.</li><li>On two small pieces of paper, write down the address or addresses where you will be staying. For safety reasons, keep details to a minimum. Retain a copy on your person, and place one copy hidden in your luggage.</li><li>On two small pieces of paper, write down 3 phone numbers that you contact (text or call) the most. Retain a copy on your person, and place one copy hidden in your luggage.</li><li>Write down your phone’s IMEI number and serial number on a piece of paper, or store them in a different account that’s not tied to your main account, or write it on two pieces of paper and store one on your person, and one hidden in your luggage.</li><li>Write down reservation numbers and phone numbers for events, accommodations, flights, trains, and public transportation in a document. Share this document with at least two loved ones.</li><li>Keep your passport in a secure place in your lodging (a locked safe for instance). However, if you need to purchase a SIM card in a foreign country, you may need to bring your passport in order to prove that you are a tourist.</li><li>If you cancel your phone plan in your home country, there may be a time limit for reactivation (mine was 30 days). Keep this in mind when you return home.</li><li>Do not add all of your credit/debit cards into your digital wallet for contactless payment. Keep some cards offline so that in the event that your device is compromised, you won’t be forced to lock or cancel those cards.</li><li>Keep some cash in your accommodations.</li></ul><p>This experience was a wake-up call about the vulnerabilities of relying too heavily on technology while traveling. While this could happen to anyone, I’m hoping these tips will encourage more of us to be proactive. Safe travels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7615701d0d4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activity-Based Bottom Navigation Using Shared Element Transition with BottomNavigationView]]></title>
            <link>https://kelvinwatson.medium.com/bottomnavigationview-for-activity-based-app-navigation-using-shared-element-transition-c4de864d400f?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4de864d400f</guid>
            <category><![CDATA[bottomnavigationview]]></category>
            <category><![CDATA[activity]]></category>
            <category><![CDATA[navigation-bar]]></category>
            <category><![CDATA[bottomnavigationbar]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 03:36:04 GMT</pubDate>
            <atom:updated>2023-09-06T22:36:37.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xj9jtUcjaSi6pQPiZaDKpQ.png" /></figure><blockquote>Using BottomNavigationView with fragments is well documented. The <a href="https://developer.android.com/codelabs/android-navigation#8">Jetpack Navigation Component </a>supports fragment-based navigation via the BottomNavigationView for top level destinations in the app. However, many apps, especially legacy Android code bases, still primarily use activities as their top level destinations. Here, we explore a potential solution using Shared Element Transition on the <em>BottomNavigationView.</em></blockquote><p>There are many reasons why migrating to fragment-based navigation can be a complex task. Sometimes, it isn’t feasible or practical to refactor an Android app that uses activity-based navigation. For instance, many legacy apps have activities that use different launch modes, deep linking logic, etc.</p><p>With apps that use activity-based navigation, migrating to the relatively newer BottomNavigationView can result in UI jank. For instance, each activity reachable by the BottomNavigationView launches a new activity, which in turn has to create a new BottomNavigationView each time it is launched. If we stick with the default activity transitions, this can result in the BottomNavigationView seeming to jump into view with every activity transition. Ideally, we’d like the BottomNavigationView to be “sticky”, or at least give the illusion of it persisting across activities.</p><p>In this article, I introduce a potential solution to migrate to BottomNavigationView navigation for apps that are heavily activity based.</p><p>Shared element transition is not new. It was introduced in Android Lollipop. It’s used for animating transitions of views when switching between activities. For instance, take this classic example from the <a href="https://developer.android.com/develop/ui/views/animations/transitions/start-activity">Android developer documentation</a> where an ImageView and a TextView are the shared elements between the two screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*WZE6fwLOZEimPgzVEPAkxw.gif" /><figcaption>shared element transitions</figcaption></figure><h3>Exploring our options</h3><h4>1. A hack?</h4><p>There is a <a href="https://www.geeksforgeeks.org/how-to-implement-bottom-navigation-with-activities-in-android/">hacky solution</a>, but it uses overridePendingTransitions(0, 0), which essentially abolishes all activity transition animations. This means that while the BottomNavigationBar visually appears to be sticky, navigating between each activity looks abrupt, each activity snapping into view without any easing. While this is an easy solve, it may not produce the desired result, as seen in the video below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*2T-4cYsYDY5ACovB2gNPmg.gif" /><figcaption>overridePendingTransition(0,0) removes all activity transitions</figcaption></figure><h4>2. Proposed solution using Shared Element Transition</h4><p>What if we used activity transitions with shared elements on the BottomNavigationBar? If we think about it, it makes some sense. The common or shared element between the activities is the BottomNavigationBar itself. Although we’re not necessarily interested in animating the BottomNavigationBar in any way, it is the common or shared element between the activities. It turns out that this solution is potentially viable for projects that cannot migrate, or need to defer migration to fragment-based bottom navigation. Let’s get started.</p><h3>Implementation</h3><p>First, add the following attributes to your app theme. windowEnterTransition and windowExitTransition are only required if you want to override the default window transitions provided by the Android system. If you’re not interested in changing those, you can leave these out. The windowSharedElementEnterTransition and windowSharedElementExitTransition values are not really important here, since we’re not actually interested in animating any aspect of the BottomNavigationBar. However, we still need to specify this so that that the app understands that there is a shared element. You can use any of the provided standard transitions provided by the Android platform: change_bounds, change_image_transform, change_transform, change_image_transform, change_clip_bounds. You could also create a no-op transition class and use that if you wish.</p><pre>&lt;&lt;style name=&quot;AppTheme&quot; parent=&quot;android:Theme.Material&quot;&gt;<br>  &lt;!-- enable window activity transitions (REQUIRED) --&gt;<br>  &lt;item name=&quot;android:windowActivityTransitions&quot;&gt;true&lt;/item&gt;<br><br>  &lt;!-- specify enter and exit transitions (OPTIONAL) --&gt;<br>  &lt;item name=&quot;android:windowEnterTransition&quot;&gt;@transition/explode&lt;/item&gt;<br>  &lt;item name=&quot;android:windowExitTransition&quot;&gt;@transition/explode&lt;/item&gt;<br><br>  &lt;!-- specify shared element transitions --&gt;<br>  &lt;item name=&quot;android:windowSharedElementEnterTransition&quot;&gt;<br>    @transition/change_image_transform&lt;/item&gt;<br>  &lt;item name=&quot;android:windowSharedElementExitTransition&quot;&gt;<br>    @transition/change_image_transform&lt;/item&gt;<br>&lt;/style&gt;</pre><p>Depending on which standard transition you used, you’ll need to define it in your res/transition folder, for instance:</p><pre>&lt;!-- res/transition/change_image_transform.xml --&gt;<br><br>&lt;transitionSet xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> tools:ignore=&quot;ResourceName&quot;&gt;<br>    &lt;changeImageTransform/&gt;<br>&lt;/transitionSet&gt;</pre><p>Next, define a shared element name for the widget, in our case the BottomNavigationView in your donottranslate.xml file.</p><pre>&lt;!-- res/values/donottranslate.xml --&gt;<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;string name=&quot;nav_view_shared_element_transition_name&quot;&gt;navigation_view_shared_element&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>Now, set that string as the android:transitionName attribute in your BottomNavigationView. You will see later why this is necessary</p><pre>&lt;!-- res/layout/activity_main.xml --&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    android:id=&quot;@+id/container_main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br><br>    &lt;!-- Rest of your activity content --&gt;<br><br>    &lt;com.google.android.material.bottomnavigation.BottomNavigationView<br>        android:id=&quot;@+id/nav_view&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;0dp&quot;<br>        android:layout_marginEnd=&quot;0dp&quot;<br>        android:background=&quot;?android:attr/windowBackground&quot;<br>        android:transitionName=&quot;@string/nav_view_shared_element_transition_name&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:menu=&quot;@menu/bottom_nav_menu&quot; /&gt;<br>&lt;/ConstraintLayout&gt;</pre><p>Now, we are ready to use the above to navigate using our BottomNavigationView.</p><p>Whenever you start a new activity from tapping on the BottomNavigationBar, you will need to set up the scene transition animation for the BottomNavigationBar. Note that I am using the base class NavigationBarView here in case your app makes use of the NavigationRailView on landscape or larger screens.</p><pre>fun NavigationBarView.startActivityWithNavBarSharedTransition(<br>    activity:Activity,<br>    intent: Intent<br>) {<br>    val options = ActivityOptions.makeSceneTransitionAnimation(<br>        activity,<br>        this,<br>        activity.getString(R.string.nav_view_shared_element_transition_name)<br>    ).toBundle()<br>    activity.startActivity(intent, options)<br>}</pre><p>This is what your MainActivity could look like:</p><pre>class MainActivity : AppCompatActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        findViewById&lt;NavigationBarView&gt;(R.id.nav_view).apply {<br>            selectedItemId = R.id.navigation_home<br>            setOnItemSelectedListener {<br>                when (it.itemId) {<br>                    R.id.navigation_notifications -&gt; {<br>                        startActivityWithNavBarSharedTransition(<br>                            this@MainActivity,<br>                            Intent(applicationContext, NotificationsActivity::class.java)<br>                        )<br>                        true<br>                    }<br><br>                    R.id.navigation_dashboard -&gt; {<br>                        startActivityWithNavBarSharedTransition(<br>                            this@MainActivity,<br>                            Intent(applicationContext, DashboardActivity::class.java)<br>                        )<br>                        true<br>                    }<br><br>                    R.id.navigation_home -&gt; true<br>                    else -&gt; false<br>                }<br>            }<br>        }<br>    }<br>}<br><br></pre><p>And voila, the app gives the illusion that the BottomNavigationBar is sticky, and we’ve kept the system’s activity transitions intact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*AWqQgvLSArnZJhSRBxePzA.gif" /><figcaption>BottomNavigationView shared element transition for activity navigation</figcaption></figure><h3>GitHub</h3><p>You can find the source code for the demo here: <a href="https://github.com/kelvinwatson/activity-based-bottom-navigation">https://github.com/kelvinwatson/activity-based-bottom-navigation</a></p><p><a href="https://www.buymeacoffee.com/kelvinwatson">Kelvin Watson is android apps, medium, muscles, bodybuilding</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4de864d400f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with the Jetpack Glance SDK]]></title>
            <link>https://kelvinwatson.medium.com/getting-started-with-jetpack-glance-641c413829e?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/641c413829e</guid>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-widget]]></category>
            <category><![CDATA[jetpack-glance]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 02:50:55 GMT</pubDate>
            <atom:updated>2023-09-05T04:22:26.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbHZ1qu9jq6GjdJBlHe9oQ.png" /></figure><p>With Jetpack Glance, you can now leverage familiarity with Compose syntax to write your app widgets. This is a brief guide to writing your own Android widgets using this new library. At the time of writing, Jetpack Glance was in beta.</p><p>This article will guide you through the set up/integration so you can focus on building the Composables for your widget.</p><p>Add the <a href="https://developer.android.com/jetpack/androidx/releases/glance">required dependencies</a> in the app or module build.gradle.kts:</p><pre>dependencies {<br>    // For Glance support<br>    implementation(&quot;androidx.glance:glance:1.0.0-beta01&quot;)<br>    <br>    // For AppWidgets support<br>    implementation(&quot;androidx.glance:glance-appwidget:1.0.0-beta01&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>NOTE: If you include the above in a separate module from your app module, you’ll need to add the dependencies to your <strong>app level</strong> <strong>build.gradle.kts</strong> as well. Otherwise your widget will not appear in the home screen’s widget selection screen.</p><pre>dependencies {<br>    // For Glance support<br>    implementation(&quot;androidx.glance:glance:1.0.0-beta01&quot;)<br>    <br>    // For AppWidgets support<br>    implementation(&quot;androidx.glance:glance-appwidget:1.0.0-beta01&quot;)<br>}</pre><p>Write your widget and widget receiver (broadcast receiver):</p><pre>object MyGlanceWidget : GlanceAppWidget() {<br><br>    override suspend fun provideGlance(context: Context, id: GlanceId) =<br>        provideContent {<br>            Text(&quot;Hello, my glance widget&quot;)<br>        }<br>}<br><br><br>class MyGlanceWidgetReceiver : GlanceAppWidgetReceiver() {<br>    override val glanceAppWidget: GlanceAppWidget<br>        get() = MyGlanceWidget<br>}</pre><p>Define the Glance provider info in res/xml/my_widget_provider_info.xml:</p><pre>&lt;appwidget-provider xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>   android:description=&quot;@string/my_app_name&quot;<br>   android:minWidth=&quot;50dp&quot;<br>   android:minHeight=&quot;50dp&quot;<br>   android:resizeMode=&quot;horizontal|vertical&quot;<br>   android:widgetCategory=&quot;home_screen&quot; /&gt;</pre><p>Update your AndroidManifest to register the broadcast receiver you wrote above:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest package=&quot;com.example.my.widget&quot;<br>   xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>   &lt;application&gt;<br><br>      &lt;receiver<br>         android:name=&quot;.MyGlanceWidgetReceiver&quot;<br>         android:exported=&quot;true&quot;&gt;<br><br>         &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt;<br>         &lt;/intent-filter&gt;<br><br>         &lt;meta-data<br>            android:name=&quot;android.appwidget.provider&quot;<br>            android:resource=&quot;@xml/my_widget_provider_info&quot; /&gt;<br>      &lt;/receiver&gt;<br>   &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Now, build the app. Long press on the home screen and select “Widgets”. Your widget will appear in the list. Drag it into your home screen and enjoy!</p><p>Dependency injection</p><p>You can also use dependency injection frameworks on Glance widgets. For instance, you would set up injection like you normally would for BroadcastReceviers, since the GlanceAppWidgetReceiver extends BroadcastReceiver. For instance, if you’re using Dagger 2, you could do the following:</p><pre>@Module<br>interface MyGlanceWidgetReceiverModule {<br>    @ContributesAndroidInjector<br>    abstract fun contributesMyGlanceWidgetReceiver(): MyGlanceWidgetReceiver<br>}</pre><p>Then, inject what you need into your GlanceWidgetReceiver to perform actions, etc:</p><pre>class MyGlanceWidgetReceiver: GlanceAppWidgetReceiver() {<br><br>    @Inject<br>    internal lateinit var myDependency: MyInjectDependency<br><br>    override fun onReceive(context: Context, intent: Intent) {<br>        AndroidInjection.inject(this, context)<br>        myDependency.execute()<br>    }<br>}</pre><p>If you liked this article, please consider supporting my page so I can bring you more articles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*5D9ZTssrYkDI-7hN0fAVkw.gif" /><figcaption>Please consider supporting me</figcaption></figure><p><a href="https://www.buymeacoffee.com/kelvinwatson">Kelvin Watson is android apps, medium, muscles, bodybuilding</a></p><p>For more information, check out the following resources:</p><p><a href="https://developer.android.com/jetpack/androidx/releases/glance">Glance | Jetpack | Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=641c413829e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Activity Inheritance with Dagger 2]]></title>
            <link>https://kelvinwatson.medium.com/android-activity-inheritance-with-dagger-2-b90517f10e4b?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b90517f10e4b</guid>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 17:35:13 GMT</pubDate>
            <atom:updated>2023-08-20T16:21:25.680Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up Dagger 2 injection for inheritance situations with Android activities or fragments can be a pain. This article explains it simply with an example.</p><p>Suppose you have a BaseActivity that you need to extend. Let’s call the extending class SubClassedActivity.</p><h3>Steps</h3><p>First, contribute the android injector for the subclassed activity.</p><pre>@Module<br>abstract class UiModule {<br>    <br>    @[ActivityScope ContributesAndroidInjector(modules = [SubClassedActivityModule::class])]<br>    abstract fun contributeSubClassedActivityInjector(): SubClassedActivity<br>}</pre><p>Define the baseActivityModule.</p><pre>@Module<br>abstract class BaseActivityModule {<br>    @Binds<br>    abstract fun bindBaseActivity(instance: BaseActivity): FragmentActivity<br>}</pre><p>Install the BaseActivityModulein the SubClassedActivityModule.</p><pre>@Module(includes = [BaseActivityModule::class])<br>abstract class SubClassedActivityModule {<br><br>    @Binds<br>    abstract fun bindSubClassedActivity(instance: SubClassedActivity): BaseActivity</pre><p>Now, let’s define the BaseActivity.</p><pre>abstract class BaseActivity : Activity()<strong>, </strong>HasAndroidInjector {<br>    @Inject<br>    lateinit var fragmentInjector: DispatchingAndroidInjector&lt;Any&gt;<br><br>    override fun androidInjector(): AndroidInjector&lt;Any&gt; = fragmentInjector<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        AndroidInjection.inject(this)<br>        super.onCreate(savedInstanceState)<br>        ...<br>    }</pre><p>Finally, define the SubClassedActivity.</p><pre>class SubClassedActivity : BaseActivity() {<br>    // no need to call AndroidInjector.inject(this)<br>}</pre><p>Please consider supporting me so I can bring you more content:</p><figure><a href="https://buymeacoffee.com/kelvinwatson"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b90517f10e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting an Android Activity from the command line]]></title>
            <link>https://kelvinwatson.medium.com/starting-an-android-activity-from-the-command-line-50a6b0504921?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a6b0504921</guid>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 17:19:14 GMT</pubDate>
            <atom:updated>2023-08-20T16:22:29.579Z</atom:updated>
            <content:encoded><![CDATA[<p>During feature development, you don’t always have access to an entry point to your feature. Perhaps that entry point is still under discussion, or perhaps the Activity you want to launch can only be accessed via a push notification, or perhaps the launching Activity to your Activity has not yet been built.</p><p>Whatever the reason, it is helpful to be able to launch an Activity from the command line.</p><h3>Starting an Android Activity from adb</h3><p>As a simple example, suppose you’re building an Activity (e.g. SecondPageActivity) within a large app, and you don’t have access to an entry point to this Activity within the launching Activity (e.g. First page activity), so we want to launch cold launch SecondPageActivity.</p><p>Within the Android sdk, we have access to the debug bridge, or adb. It is located in your /Library/Android/sdk/platform-tools folder.</p><p>Use this command to launch SecondPageActivity:</p><pre>./adb shell am start -n com.example.my.app/. SecondPageActivity --es &quot;Message&quot; &quot;hello!&quot;</pre><p>The above means start the SecondPageActivity with a strong intent extra.</p><p>If you’re using a device or emulator running API 23 or under, this should work as expected, i.e. SecondPageActivity will be launched.</p><p>However, if you try to do this with an emulator or device running API above 23, you may encounter this error:</p><pre>Security exception: Permission Denial: starting Intent { act=android.intent.action.RUN flg=0x30000000 cmp=com.example.my.app/SecondPageActivity (has extras) } from null (pid=4729, uid=2000) <strong>not exported</strong> from uid 10079</pre><p>To remedy this, create a debug package in your module and add an AndroidManifest.xml file. This AndroidManifest.xml should be identical to the one in your main package, except that the activity tag includes the exported=&quot;true&quot; attribute.</p><p>This debug manifest will be used when building the debug app variant so that you can use the above adb command to launch your Activity in devices running API higher than 23.</p><p>Please consider supporting me so I can bring you more content:</p><figure><a href="https://buymeacoffee.com/kelvinwatson"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a><figcaption>Please consider buying me a coffee!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a6b0504921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Injecting an interface with Dagger 2]]></title>
            <link>https://kelvinwatson.medium.com/injecting-an-interface-with-dagger-2-728d6353837d?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/728d6353837d</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-android]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 03:45:30 GMT</pubDate>
            <atom:updated>2023-08-20T16:23:07.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Injecting an interface with Dagger 2 in a multi-module Android project</h3><p>In a multi-module Android project, you can use Dagger 2 to inject an interface, even if one module cannot access the implementation that lives in another module.</p><p>In this article, I’ll show you how to access a concrete implementation in an upstream module.</p><p>This article assumes some knowledge in Android development and familiarity with the <a href="https://dagger.dev/">Dagger 2</a>/<a href="https://dagger.dev/android">Dagger-Android</a> library.</p><h3>Let’s go through an example</h3><p>Let’s say you have an Android project consisting of 2 modules: :appand :myModule. In our example,:app depends on :myModule.</p><p>In your :app’s build.gradle:</p><pre>dependencies {<br>    implementation project(&#39;:myModule&#39;)<br>}</pre><p>Then, let’s say that :app contains the class Person:</p><pre>class Person @Inject constructor() </pre><p>Let’s suppose that now, you want to access Person in :myModule. However, that’s not possible. Remember that :app depends on :myModule and not the other way around.</p><h3>Expose the interface, not the implementation</h3><p>How can we access a concrete implementation ofPerson from :myModule?</p><p>Create an interface in :myModule:</p><pre>/** <br> * Interface for use in Dagger 2<br> */<br>interface PersonContract</pre><p>Have Person in the :app module implement the interface:</p><pre>class Person @Inject constructor() : PersonContract</pre><p><em>Remember that </em><em>:app has access to </em><em>:myModule&#39;s classes</em></p><p>Now, expose Person in one of your :app’s Dagger modules</p><pre>@Module<br>abstract class AppModule {<br><br>    @ActivityScope<br>    @ContributesAndroidInjector(modules = [MyActivityModule::class])<br>    abstract fun contributeMyActivityInjector(): MyActivity<br><br>    <strong>@Binds<br>    abstract fun bindPersonContract(person: Person): PersonContract<br></strong>}</pre><p>Now, assuming you have Dagger injection set up in both :app and :myModule, you can now inject a Person in :myModule by simply injecting PersonContract.</p><pre>package com.example.mymodule</pre><pre>class MyActivity : AppCompatActivity(), HasAndroidInjector {<br>    <br>    <strong>// This will be the concrete instance</strong>   <strong> <br>    @Inject<br>    lateinit var person: PersonContract <br></strong><br>    @Inject<br>    lateinit var androidInjector: DispatchingAndroidInjector&lt;Any&gt;<br><br>    override fun androidInjector(): AndroidInjector&lt;Any&gt; = androidInjector<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        AndroidInjection.inject(this)<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_my</em>)<br>    }<br>}</pre><p>What is happening here?</p><p>:myModule does not have access to Person. However, Dagger 2 still knows how to construct a Person since we bound the Personto the interface PersonContract.</p><p>Please consider supporting me so I can bring you more content:</p><figure><a href="https://www.buymeacoffee.com/kelvinwatson"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=728d6353837d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cronet integration with LiveData and Kotlin Coroutines]]></title>
            <link>https://kelvinwatson.medium.com/cronet-integration-with-livedata-and-kotlin-coroutines-bf6a3db85544?source=rss-55165c04ec5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf6a3db85544</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Kelvin Watson]]></dc:creator>
            <pubDate>Sat, 16 Nov 2019 23:07:03 GMT</pubDate>
            <atom:updated>2023-08-20T16:23:47.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cronet integration with LiveData and Kotlin Coroutines on Android</h3><p><a href="https://developer.android.com/guide/topics/connectivity/cronet">Cronet</a> is a Chromium library used to handle network requests. It’s used on a number of Google products, including YouTube and Google Maps.</p><h3>Purpose</h3><p>While there are many working Android code examples of usage of Kotlin coroutines, LiveData and the network library <a href="https://square.github.io/retrofit/">Retrofit</a>, there isn’t an example of the specific combination of Cronet in the context of LiveData and coroutines.</p><h3>The Cronet documentation’s sample code shows a traditional callback structure (see `Url ). However, not included in that documentation is how Cronet can be integrated with Kotlin Coroutines and LiveData. The following example bridges this gap.</h3><h3>Prerequisites</h3><p>In addition to modern Android development paradigms, it is assumed that you have some knowledge of <a href="https://dagger.dev/">Dagger 2/Dagger-Android</a> dependency injection. Basic information about Cronet can be found <a href="https://developer.android.com/guide/topics/connectivity/cronet/start">here</a>.</p><h3>Setup</h3><p>For this particular example, we’ll want to include the Cronet library (as well as its less performant fallback in the case that it can’t be loaded from Google Play Services), as well as the latest LiveData-Ktx library. More details <a href="https://developer.android.com/guide/topics/connectivity/cronet/start">here</a>.</p><pre>// Cronet<br>implementation &#39;com.google.android.gms:play-services-cronet:16.0.0&#39;<br>// fallback <br>implementation group: &#39;org.chromium.net&#39;, name: &#39;cronet-fallback&#39;, version: &#39;76.3809.111&#39;<br><br>// LiveData builder<br>implementation group: &#39;androidx.lifecycle&#39;, name: &#39;lifecycle-livedata-ktx&#39;, version: &#39;2.2.0-rc02&#39;</pre><h3>Architecture</h3><p>Following current Android architecture component guidelines and patterns for use of <a href="https://developer.android.com/topic/libraries/architecture/coroutines">LiveData and coroutines</a>, we have the following code samples showing a standard fragment, Android ViewModel and repository .</p><h4>CustomFragment.kt</h4><p>In the fragment, we instantiate our view model and observe the LiveData object for changes.</p><pre>class CustomFragment : Fragment() {<br>    @Inject<br>    lateinit var viewModelFactory: ViewModelProvider.Factory<br>    private val customViewModel: CustomViewModel by <em>viewModels </em><strong>{<br>        </strong>viewModelFactory<br>    <strong>}<br><br>    </strong>override fun onAttach(context: Context) {<br>        AndroidSupportInjection.inject(this)<br>        super.onAttach(context)<br>        customViewModel.viewModelListLiveData.observe(this, <br>            <em>Observer </em><strong>{<br>  </strong>              onViewModelListChanged(it)      <br>            <strong>}</strong>)<br>    }<br>}</pre><h4>CustomViewModel.kt</h4><p>In the view model, we call the repository to get the LiveData. Note the emitSource call. This is similar to calling MediatorLiveData.addSource, where one liveData object observes another. In this case, myItemList is observing myItemLiveData. When myItemLiveData changes (e.g. is fetched), this triggers the Transformations.map callback.</p><pre>class CustomViewModel @Inject constructor(private val repository: Repository) : ViewModel() {<br><br>    private var myItemsLiveData: LiveData&lt;List&lt;MyItem&gt;&gt;<br><br>    init {<br>        myItemsLiveData = <em>liveData</em>(Dispatchers.IO) <strong>{<br>            </strong>val myItemsLiveData = repository.getMyItemsLiveData()<br>            emitSource(myItemsLiveData)<br>        <strong>}<br>    </strong>}<br><br>    val viewModelListLiveData: LiveData&lt;ArrayList&lt;MyItem&gt;&gt; =<br>        Transformations.map(myItemsLiveData) <strong>{ </strong>myItems <strong>-&gt;<br>            </strong>//transform to view models<br>            val viewModels = ArrayList&lt;MyItem&gt;()<br>            for (mItem in myItems) {<br>                viewModels.add(MyItemViewModel(mItem))<br>            }<br>            viewModels<br>        <strong>}<br></strong>}</pre><h4>CustomRepository.kt</h4><p>Following the Android developer documentation on how to send a simple network request using <a href="https://developer.android.com/guide/topics/connectivity/cronet/start">Cronet</a>, we have the following repository implementation.</p><blockquote>The Cronet documentation’s sample code shows a traditional callback structure (see <a href="https://developer.android.com/guide/topics/connectivity/cronet/reference/org/chromium/net/UrlRequest.Callback">UrlRequest.Callback</a>). However, not included in that documentation is how Cronet can be integrated with Kotlin Coroutines and LiveData. The following example bridges this gap.</blockquote><p>The repository snippet below makes the network call look synchronous. That’s the beauty of Kotlin coroutines. Internally, it uses the latest <a href="https://developer.android.com/topic/libraries/architecture/coroutines">LiveData builder</a> and wraps the UrlRequest.Callback implementation in a suspendCoroutine. Don’t worry, we’ll go through how all of that works.</p><pre>class CustomRepository @Inject constructor(private val context: Context, private val gson: Gson) : Repository {<br>    private val coroutineDispatcher = Executors.newSingleThreadExecutor().<em>asCoroutineDispatcher</em>()<br><br>    override suspend fun getMyItemsLiveData() = <em>liveData</em>(coroutineDispatcher) <strong>{<br>        </strong>val result: List&lt;MyItem&gt; = getMyItemsLiveDataInternal()<br>        emit(result) <strong>// emit the result back to the view model</strong><br>    <strong>}</strong></pre><h3>Analysis of CustomRepository.kt</h3><p>Looking at the <a href="https://developer.android.com/guide/topics/connectivity/cronet/start#create">Cronet documentation for performing a simple network request</a>, we see a traditional callback structure, where we can act on the result of the network calls (function bodies are omitted for brevity):</p><pre>class MyUrlRequestCallback : UrlRequest.Callback() {</pre><pre>    override fun onRedirectReceived(request: UrlRequest?, info: UrlResponseInfo?, newLocationUrl: String?) { //... }<br><br>    override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) { //... }<br><br>    override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) { //... }<br><br>    override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) { //... }<br>}</pre><p>How can we convert this into a structure where we can emit the final result from the LiveData builder back to our Android ViewModel?</p><p>Notice in the Cronet official documentation that the request runs on a single thread Executor.</p><pre>val executor: Executor = Executors.newSingleThreadExecutor()</pre><p>We can use the asCoroutineDispatcher extension function to convert this to a coroutineDispatcher to run the request as a coroutine.</p><pre>val coroutineDispatcher = Executors.newSingleThreadExecutor().<em>asCoroutineDispatcher</em>()<br><br>    override suspend fun getMyItemsLiveData(): <br>LiveData&lt;List&lt;MyItem&gt;&gt; = <em>liveData</em>(coroutineDispatcher) <strong>{ // ... }</strong></pre><p>Now we follow the Cronet documentation example of creating and starting the network request. This part is straight forward, except for the MyUrlRequestCallback()as noted below.</p><pre>val requestBuilder = cronetEngine.newUrlRequestBuilder(<br>        &quot;https://www.example.com&quot;,<br>        MyUrlRequestCallback(), // how can we call emit from here?<br>        executor<br>)<br><br>val request: UrlRequest = requestBuilder.build()<br>request.start()</pre><p>This traditional callback structure presents an issue. In CoroutineLiveData, we need to call emit to send our result back to the ViewModel. Unfortunately, if we look at the signature for emit, we see that it is a suspend function, which must be run from another suspend function or a coroutine.</p><pre><em>/**<br> * Set&#39;s the [LiveData]&#39;s value to the given [value]. If you&#39;ve called [emitSource] previously,<br> * calling [emit] will remove that source.<br> *<br> * Note that this function suspends until the value is set on the [LiveData].<br> *<br> * </em><strong><em>@param </em></strong><em>value The new value for the [LiveData]<br> *<br> * </em><strong><em>@see </em></strong><em>emitSource<br> */<br></em>suspend fun emit(value: T)</pre><p>Thankfully, we can “flatten” the callback structure by using suspendCoroutine, abstracting the Cronet invocation and callback into an internal function.</p><pre>private suspend fun getMyItemsLiveDataInternal() = </pre><pre><em>    </em><strong><em>suspendCoroutine</em></strong>&lt;List&lt;MyItem&gt;&gt; <strong>{ continuation</strong> <strong>-&gt;<br><br>        </strong>val executor = Executors.newSingleThreadExecutor()<br>        val cronetEngineBuilder = CronetEngine.Builder(context)<br>        val cronetEngine = cronetEngineBuilder.build()<br>        val requestBuilder = cronetEngine.newUrlRequestBuilder(<br>            &quot;http://example-api.com/example&quot;,<br>            object : UrlRequest.Callback() {<br><br>                override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) {<br>                    val httpStatusCode = info?.<em>httpStatusCode</em><br>                    val myBuffer: ByteBuffer = ByteBuffer.allocateDirect(32 * 1024)<br>                    if (httpStatusCode == 200) {<br>                        request?.read(myByteBuffer)<br>                    }<br><em>                </em>}<br><br>            override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, buffer: ByteBuffer?) {<br>                    buffer?.flip()<br>                    buffer?.<em>let </em><strong>{<br>                        </strong>val bytes = ByteArray(<strong>it</strong>.remaining())<br>                        <strong>it</strong>.get(bytes)<br>                        <em>String</em>(bytes, Charset.forName(&quot;UTF-8&quot;))<br>                    <strong>}</strong>.<em>apply </em><strong>{<br></strong>                        val myItems = gson.fromJson(this, MyItem::class.<em>java</em>)<br><strong>                        continuation.<em>resume</em>(</strong>myItems<strong>)<br>    </strong>                <strong>}<br>            </strong>       buffer?.clear()<br>                   request?.read(buffer)<br>                }<br><br>                // other callbacks omitted for brevity<br>            },<br>            executor<br>        )<br>        val request: UrlRequest = requestBuilder.build()<br>        request.start()<br>    <strong>}<br>}</strong></pre><p>The key here is the continuation callback parameter. Execution of the coroutine is suspended while the network call is in flight. Once the we have our network data, we can resume the coroutine by calling continuation.resume, thereby emitting our result.</p><p>Our original problem was that emit could not be called without a surrounding coroutine/suspending function. This flattening process of converting a traditional callback to a coroutine has also solved that problem since emit now lives within the LiveData builder.</p><pre>override suspend fun getMyItemsLiveData() = <em>liveData</em>(dispatcher) <strong>{<br>    </strong>val result: List&lt;MyItem&gt; = getMyItemsLiveDataInternal()<br>    emit(result)<br><strong>}</strong></pre><p>I hope you found this article helpful. Please leave comments below if anything requires further clarification. I will be updating this article as I continue developing in Kotlin.</p><p>Please consider supporting me so I can bring you more content:</p><figure><a href="https://buymeacoffee.com/kelvinwatson"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf6a3db85544" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>