<?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[HealthifyMe Tech - Medium]]></title>
        <description><![CDATA[The HealthifyMe Tech Blog &amp; Articles - Medium]]></description>
        <link>https://medium.com/healthify-tech?source=rss----c612c26b989f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>HealthifyMe Tech - Medium</title>
            <link>https://medium.com/healthify-tech?source=rss----c612c26b989f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:11:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/healthify-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ViewModel: What, Why & How?(Part-2)]]></title>
            <link>https://medium.com/healthify-tech/viewmodel-what-why-how-part-2-d47cda05822e?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/d47cda05822e</guid>
            <category><![CDATA[android-projects]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Harjot Singh]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 13:34:23 GMT</pubDate>
            <atom:updated>2022-03-25T13:34:23.092Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read Part 1, I’d suggest please go through it to get a basic understanding of ViewModel. Here’s the<a href="https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f"> link</a> to it.</p><p><a href="https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f">https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f</a></p><h3>What we’ll be making:</h3><p>This sample was created just to explain the fact that the data inside ViewModel can survive configuration changes w/o losing the data(rotation of screen for this example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQVJ_luDWsP_V_4t57tuaw.gif" /></figure><h3>Let’s understand the how now…</h3><p><strong>Step 1: Create a basic XML layout like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*evUsuE0ljyCPb_obW0qKTw.png" /></figure><p>So, one Button and one TextView.</p><p>Here’s the XML code for you to save time:</p><pre><em>&lt;?</em>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;<em>?&gt;<br></em>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tv_score&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;@string/_0&quot;<br>        android:textSize=&quot;36sp&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:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/btn_add&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;24dp&quot;<br>        android:text=&quot;@string/add&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/tv_score&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><strong>Step 2: Create your ViewModel class</strong></p><pre>class MainViewModel : ViewModel() {<br>    private val _score = MutableLiveData&lt;Int&gt;(0)<br>    val score: LiveData&lt;Int&gt; = _score<br>    fun addScore() {<br>        _score.<em>value </em>= _score.<em>value</em>?.plus(1)<br>    }<br>}</pre><p>In this code snippet, MainViewModel extends ViewModel class. We have a _score variable as MutableLiveData(with initial value as zero) i.e. it’s value can be changed, since it’s mutable. The type we are using for mutable live data is that of Int, the reason being score will be a Int value.</p><p>Then addScore() is the functionality for button click. It adds one to the _score every time user clicks on ADD button.</p><p>If you don’t know how to work with LiveData, I’d suggest to go through the above <a href="https://medium.com/@harjotsingh01/working-with-livedata-and-viewmodel-225650bd4507">article</a> too but for now let’s just copy the code.</p><p><a href="https://medium.com/@harjotsingh01/working-with-livedata-and-viewmodel-225650bd4507">Working with LiveData and ViewModel</a></p><p><strong>Step 3: Add the functionality in your MainActivity.java file</strong></p><p>Since, ViewBinding is used here, let’s add the code required to use it in the <strong>module level gradle file</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*A0svJyjECjpoGaGvmJj89g.png" /></figure><pre>//Add this inside <strong>android</strong> code block : android {...}<br>buildFeatures<strong>{<br>    </strong>viewBinding true<br><strong>}</strong></pre><p>Let’s go through the code now…</p><pre><br>class MainActivity : AppCompatActivity() {<br>    private val binding by <em>lazy </em><strong>{<br>        </strong>ActivityMainBinding.inflate(<em>layoutInflater</em>)<br>    <strong>}<br>    </strong>private lateinit var viewModel: MainViewModel<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(binding.<em>root</em>)</pre><pre>        // a. initialising viewModel<br>        viewModel = ViewModelProvider(this)<br>                    .get(MainViewModel::class.<em>java</em>)<br>        val scoreText = binding.tvScore<br>        val addBtn = binding.btnAdd</pre><pre>        // b. button functionality<br>        addBtn.setOnClickListener <strong>{<br>            </strong>viewModel.addScore()<br>        <strong>}<br>       </strong>//c. Observing the live data <br>        viewModel.score.observe(this) <strong>{ </strong>score <strong>-&gt;<br>            </strong>scoreText.<em>text </em>= score.toString()<br>        <strong>}<br><br>    </strong>}<br>}</pre><p><strong>Confusing…? Okay, let’s go through it point by point:</strong></p><p><strong>a. Initialising ViewModel<br> ViewModelProvider</strong> is a class that creates ViewModels and retain them in a store of given <strong>ViewModelStoreOwner</strong>. Here, we’ve passed <strong>this</strong> as the owner.</p><p><strong>b. Button functionality<br></strong>Here, we called out a method from viewModel, basically doing separation of concerns. This method adds one to the existing score.</p><p><strong>c. Observing the LiveData<br></strong>Now, we are simply observing the changes that would happen inside LiveData.</p><p>For a better understanding, here’s how the flow works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_OgitFdCxftvMs0pZ875A.png" /></figure><p>Thank you for reading! <br>Here’s part -1 of this story:</p><p><a href="https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f">https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d47cda05822e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/viewmodel-what-why-how-part-2-d47cda05822e">ViewModel: What, Why &amp; How?(Part-2)</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViewModel: What, Why & How (Part-1)]]></title>
            <link>https://medium.com/healthify-tech/viewmodel-what-why-how-part-1-3cd9ac479f7f?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/3cd9ac479f7f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodelscope]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Harjot Singh]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 13:04:55 GMT</pubDate>
            <atom:updated>2022-03-25T13:04:55.833Z</atom:updated>
            <content:encoded><![CDATA[<p>I know…I know, you might have heard a lot about ViewModel during your learning phase. I got to know more about it during my ongoing Internship with HealthifyMe and trust me, it is such a saviour. It is highly used in the Android World plus without this, learning Android Architecture is going to be so confusing. But no worries, I’m here to the rescue :)</p><p>So, without any further ado, let’s hop into the material:</p><p>Part -1 is focused on What and Why.</p><p>Part -2 will focus on the How part of the story. <br>(Building a small project basically)</p><p>(Feel free to jump into any of the parts)</p><h3>What is a ViewModel?</h3><p><strong>ViewModel</strong> is a part of android architecture components(More on android architecture in a different blog). ViewModel class stores and manages UI data in a lifecycle-conscious way.</p><p>But wait…! Why we need a view model when we can use <strong>onSaveInstanceMethod()</strong>. Let’s find out.</p><h3>Why ViewModel?</h3><p>The primary reason would be to survive configuration changes and not lose data.</p><p>During configuration changes, the activity recreates itself i.e. <strong>onDestroy()</strong> gets called, then again <strong>onCreate()</strong> is called. Hence, any change to the activity’s view like changing value of textView will be lost and it’d change back to its default value.</p><p><strong><em>ViewModel comes to the rescue.</em></strong></p><p>ViewModel objects are also <strong>lifecycle-aware</strong> i.e. they are automatically cleared when the Lifecycle they are observing gets destroyed permanently. Henceforth, viewModels are not destroyed if the activity gets recreated... its instance remains (<a href="https://developer.android.com/topic/libraries/architecture/saving-states#options">Except on low memory situation</a>, keep an eye on this).</p><p>Here’s a diagram to help you visualize as how things work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*scFWc9pigItDwMHD3Bv_Sw.png" /></figure><p>ViewModel’s instance is destroyed when <strong>onCleared()</strong> is called.</p><p>Yes… <strong>onSaveInstanceState()</strong> can save the data and then it can be restored from <strong>savedInstanceState</strong> bundle in <strong>onCreate()</strong> method. But, this is suitable only for simple data…not for a data which contains a list of users, employee or any other large amount of data.</p><p>Second reason as to why ViewModel is that it helps in pursuing separation of concerns. This is one concept which is religiously followed in Android Architecture like MVVM.</p><p>Overview to this concept would be delegating the tasks and not overloading the activity or fragment classes. According to the Android Architecture, UI…UI logic…Business logic should be contained in separate classes. UI contains activity and fragments whose sole purpose is to display the data.<br>ViewModel contains the UI logic i.e. it takes the data that needs to be displayed in UI components.</p><p>Third reason would be better testing. Since, each class would be responsible for something, it is way easier to run tests with more than 70% of code coverage.</p><h3>Important Points to take care of …</h3><p>*<strong> ViewModel</strong> does not know to which view it’s setting the data.</p><p>* <strong>ViewModel</strong> notifies UI through observers like LiveData.</p><p>* <strong>ViewModel</strong> should not contain any reference to a view. This may cause memory leaks since viewModel has a different lifecycle scope than activity &amp; fragments.</p><p>* Extend <strong>AndroidViewModel</strong> if you still need to use context in your code. We can pass application context to AndroidViewModel.</p><p>I’ve created a simple project to explain how the viewmodel retains its state during configuration changes like screen rotation.</p><p>Thank you for reading! Please give it a clap, this would motivate me to make more of medium blogs.<br>Until then, Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cd9ac479f7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/viewmodel-what-why-how-part-1-3cd9ac479f7f">ViewModel: What, Why &amp; How (Part-1)</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with LiveData and ViewModel]]></title>
            <link>https://medium.com/healthify-tech/working-with-livedata-and-viewmodel-225650bd4507?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/225650bd4507</guid>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[view-binding]]></category>
            <dc:creator><![CDATA[Harjot Singh]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 12:50:27 GMT</pubDate>
            <atom:updated>2022-03-25T12:50:27.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Owl" src="https://cdn-images-1.medium.com/max/1024/0*6Omx9iBqUy49qWvP" /><figcaption>Photo by <a href="https://unsplash.com/@brock222?utm_source=medium&amp;utm_medium=referral">Richard Lee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction:</strong></h3><p>LiveData is an Observable data class. Unlike RxJava’s Observable it is lifecycle-aware which means it notifies Observer objects only when the app components like Activity, Fragment or Service is in <strong>active</strong> state.</p><p>Active state is when the app component’s lifecycle is in <strong>STARTED</strong> or <strong>RESUMED</strong> state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIk03U6BVC3AMubTWo4m6A.png" /></figure><p>In the diagram above, LiveData could be modified from ViewModel and here Observers are the app components that have Android lifecycle i.e. activity or fragment. Since Observer{1,4,5} are in<strong> active</strong> state(STARTED or RESUMED), LiveData notifies these observer objects while the Observers{2,3} with the <strong>inactive</strong> state(PAUSED or DESTROYED) won’t be getting notified about the updates from LiveData object.</p><h3><strong>Why to use LiveData?</strong></h3><p>a. Lifecycle-aware : Because LiveData is lifecycle aware, let me re-iterate, it will notify those observer objects which are in active state.</p><p>b. The UI can be updated more easily. Whenever the data change happens, it will notify the observers about the changes.</p><p>c. The Observer objects clean up themselves when the associated lifecycle is destroyed. (In RxJava, we have to handle unsubscribing of Observer in <strong>PAUSED</strong> or <strong>DESTROYED</strong> state)</p><h3><strong>MutableLiveData and LiveData</strong></h3><p>a. MutableLiveData, as the name suggests, is mutable i.e. it’s value can be changed whereas, LiveData is read-only.</p><p>b. LiveData is an abstract class and MutableLiveData is a child of it.</p><p>c. LiveData is always initialized with one of it’s child class’s constructors except Transformation and MediatorLiveData.</p><h3><strong>Implementation</strong></h3><p>Let’s quickly go through the sample project that I’m working on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*wuQcXUVVg2KmEFdu2xbA9w.png" /></figure><p>In this project, we have an activity with one TextView and two Buttons.<br>Change Text Button will change the text of the TextView and Undo Text Button replaces with the text with “Hello World!”. I have used ViewBinding for this project. The blog for ViewBinding will be written shortly, so stay tuned for that. :)</p><p>Now enough talking, let’s jump into the good stuff<strong>:</strong></p><p><strong>Step 1: </strong>Initializing LiveData in our ViewModel</p><pre>val mLiveData = MutableLiveData&lt;String&gt;()</pre><p>a. <strong>mLiveData</strong> is declared as <strong>val</strong>, so it cannot change but it’s <strong>value</strong> can always be updated. Now, any change in its value would notify the observers about it.</p><p>But wait….doesn’t this mean that <strong>mLiveData</strong> can be changed from any class inside the project….. now enters accessibility modifier into the picture: we’ll make it <strong>private</strong>.</p><p>Okay…good solution, but then how can we access the LiveData then?</p><p>The answer is simple. Remember, LiveData is read only?<br>We’ll take that into the picture. So the code becomes:</p><pre>private val mLiveData = MutableLiveData&lt;String&gt;()</pre><pre>fun getLiveData(): LiveData&lt;String&gt; = mLiveData</pre><p>b. The <strong>type</strong> of MutableLiveData here is <strong>String</strong> because we want to observe the text that would be changing in the activity.</p><p><strong>Step 2: </strong>Initialize viewModel inside our MainActivity class</p><pre>private val viewModel = ViewModelProvider(this)<br>                        .get(MyViewModel::class.<em>java</em>)</pre><p><strong>ViewModelProvider</strong> is a class that creates ViewModels and retain them in a store of given <strong>ViewModelStoreOwner</strong>. Here, we’ve passed as <strong>this</strong> as the owner.</p><p><strong>Step 3: </strong>Observe the live data</p><pre>//textView is the Text with &quot;Hello World!&quot; <br>viewModel.getLiveData().observe(this) <strong>{ </strong>text <strong>-&gt;<br>    </strong>textView.<em>text </em>= text<br><strong>}<br>                           OR</strong></pre><pre><strong>//</strong>this function can also be written as <br>viewModel.getLiveData().observe(this,Observer<strong>{ </strong>text <strong>-&gt;<br>    </strong>textView.<em>text </em>= text<br><strong>}) </strong></pre><pre>//both do the same work...so don&#39;t you get confused</pre><p><strong>observe()</strong> takes <strong>LifecycleOwner</strong> and <strong>Observer</strong> as its argument.</p><p>(Note: LifecycleOwner in simple words is a class that has Android lifecycle)</p><p>Alright, now we have created LiveData, intialized ViewModel, started observing the data. But, how the LiveData’s value will keep on changing?</p><p><em>In real scenarios, the data gets changed by backend and then liveData is needed, but in our example, we’ll kinda do it in a hacky way.<br>Let’s change the text when “Change text” button is clicked. Consider it as a data change from API; when the value of LiveData changes, the observer would notify about it in the MainActivity.</em></p><p>So, we’ll create a new method<strong> changeText()</strong> inside our ViewModel class which would be called whenever “Change text” button is clicked.</p><p><strong>Inside MainActivity class</strong></p><pre>btnChangeText.setOnClickListener <strong>{<br>    </strong>viewModel.changeText()<br><strong>}</strong></pre><p><strong>Inside ViewModel class</strong></p><pre>fun changeText(){<br>    mLiveData.<em>value </em>= &quot;The text has been changed&quot;<br>}</pre><p>And there it is…phew! <br>Finally done!</p><p>Let’s see the results now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kR7ovMJ_NyvMpUtvGVl-Cw.gif" /></figure><p>To save you time, I have copy pasted the code here and it’ll be available on my Github link too. So either copy from here and paste into your project or clone the project from Github. Cheers!</p><h3>CODE:</h3><p><em>activity_main.xml</em></p><pre><em>&lt;?</em>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;<em>?&gt;<br></em>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.presentation.MainActivity&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tv_text&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello World!&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/btn_change_text&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;24dp&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/tv_text&quot;<br>        app:layout_constraintStart_toStartOf=&quot;@id/tv_text&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;@id/tv_text&quot;<br>        android:textAllCaps=&quot;false&quot;<br>        android:text=&quot;Change Text&quot;/&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/btn_undo_text&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;24dp&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/btn_change_text&quot;<br>        app:layout_constraintStart_toStartOf=&quot;@id/tv_text&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;@id/tv_text&quot;<br>        android:textAllCaps=&quot;false&quot;<br>        android:text=&quot;Undo Text&quot;/&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><em>MainActivity.kt</em></p><pre>import android.os.Bundle<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.lifecycle.ViewModelProvider<br>import com.example.livedatapractice.databinding.ActivityMainBinding<br>import com.example.livedatapractice.viewmodel.MyViewModel</pre><pre>class MainActivity : AppCompatActivity() {<br>    private val binding by <em>lazy </em><strong>{<br>        </strong>ActivityMainBinding.inflate(<em>layoutInflater</em>)<br>    <strong>}</strong></pre><pre><strong>    </strong><em>//initializing viewModel lazily too<br>    </em>private val viewModel: MyViewModel by <em>lazy </em><strong>{<br>        </strong>ViewModelProvider(this).get(MyViewModel::class.<em>java</em>)<br>    <strong>}<br><br>    </strong>override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(binding.<em>root</em>)<br>        val btnChangeText = binding.btnChangeText<br>        val btnUndoText = binding.btnUndoText<br>        val textView = binding.tvText<br><br>        <em>//Observing the live data<br>        </em>viewModel.getLiveData().observe(this) <strong>{ </strong>text <strong>-&gt;<br>            </strong>textView.<em>text </em>= text<br>        <strong>}<br><br>        </strong>btnChangeText.setOnClickListener <strong>{<br>            </strong>viewModel.changeText()<br>        <strong>}<br>        </strong>btnUndoText.setOnClickListener <strong>{<br>            </strong>textView.<em>text </em>= &quot;Hello World!&quot;<br>        <strong>}<br>    </strong>}<br>}</pre><p><em>MyViewModel.kt</em></p><pre>import androidx.lifecycle.LiveData<br>import androidx.lifecycle.MutableLiveData<br>import androidx.lifecycle.ViewModel</pre><pre>class MyViewModel: ViewModel() {</pre><pre><em>    </em>private val mLiveData = MutableLiveData&lt;String&gt;()<br><br>    <em>/* Now live data is read only, henceforth we need not worry about the value being changed<br>    through some other class&#39;s code. */<br>    </em>fun getLiveData(): LiveData&lt;String&gt; = mLiveData<br><em><br>    </em>fun changeText(){<br>        mLiveData.<em>value </em>= &quot;The text has been changed&quot;<br>    }<br>}</pre><h3>Thank you for reading :) <br>Happy coding!</h3><p>By: <a href="https://medium.com/u/a7e308ec815e">Harjot Singh</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=225650bd4507" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/working-with-livedata-and-viewmodel-225650bd4507">Working with LiveData and ViewModel</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coil Vs Glide]]></title>
            <link>https://medium.com/healthify-tech/coil-vs-glide-3f488f4de72a?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/3f488f4de72a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[image-loader]]></category>
            <category><![CDATA[coils]]></category>
            <category><![CDATA[glide]]></category>
            <dc:creator><![CDATA[Singhparakram]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 05:46:41 GMT</pubDate>
            <atom:updated>2021-12-27T05:46:41.168Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will do a comparison between Glide and Coil and make an understanding about which one is better right now.</p><p>Glide is a fast and efficient open-source image loading framework for Android which a large number of people are using, whereas Coil is a new library that is gaining popularity these days. Basic functionalities for both the libraries are the same; they both use BitmapFactory to decode the data and use the same Android SDK APIs to read data from the file.</p><p>So why is its popularity increasing and how is it different from glide?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUcrtCqbxbn9Emv8tqawiw.png" /></figure><p>It is the only image loading library that is backed by Kotlin Coroutine. It is using libraries like Coroutines, OkHttp, Okio, AndroidX Lifecycles which are already being used in the android project, thus making it lightweight. But to choose which one is good, we have to compare their performance.</p><p>How can we compare performance?</p><p>I have created two small projects using Glide in one and Coil in the other respectively. This is a simple project which loads five images and sets them in a grid recyclerView. With these projects, we are comparing the image loading speed of each library.</p><p>This article is based on the current latest version of Glide and Coil for analysis</p><p>For Coil:</p><pre>implementation(&quot;io.coil-kt:coil:1.4.0&quot;)</pre><p>For Glide:</p><pre>implementation &#39;com.github.bumptech.glide:glide:4.12.0&#39;</pre><p>Code to load image and calculate loading time:</p><p>For Glide :</p><pre>fun ImageView.loadImage(url: String, context: Context, position: Int) {<br>    val t = System.currentTimeMillis()<br>    Glide.with(context).load(url).placeholder(R.drawable.<em>ic_launcher_background</em>).into(object : CustomTarget&lt;Drawable&gt;() {<br>        override fun onLoadCleared(placeholder: Drawable?) {<br>        }<br>        override fun onResourceReady(resource: Drawable, transition: Transition&lt;in Drawable&gt;?) {<br>            this@loadImage.setImageDrawable(resource)<br>            Log.d(&quot;LoadImage&quot;, &quot;$position           ${System.currentTimeMillis()-t}&quot;)<br>        }<br>    })<br>}</pre><p>For Coil :</p><pre>private fun ImageView.loadImage(url: String, position: Int) {<br>    val t = System.currentTimeMillis()<br>    this.<em>load</em>(url) <strong>{<br>        </strong>target <strong>{ </strong>drawable <strong>-&gt;<br>            </strong>this@loadImage.setImageDrawable(drawable)<br>            Log.d(&quot;LoadImage&quot;, &quot;$position         ${System.currentTimeMillis()-t}&quot;)<br>        <strong>}<br>    }<br></strong>}</pre><p>Below are the graphs that tell the time taken to load the image in recyclerView.</p><p>To make the test more accurate, we ran the app five times, and then we took the average of each value.</p><p><em>These tests are done on the 4G network device.</em></p><p>There are two tests one with small size images and one with large size:</p><p><em>With Small size images:</em></p><p>When images are loaded for the first time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HXeJkpvcheS7BCge" /></figure><p>When images are loaded from cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*srQOdbhiaQQ2Zenz" /></figure><p><em>With Large size images:</em></p><p>When images are loaded for the first time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pu5eXJEj6F2GFP9watJGA.png" /></figure><p>When images are loaded from cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xop7xjRGFr3lneCmJKUbuQ.png" /></figure><p>From these results, for now, in terms of performance Glide is comparatively faster than Coil but if you have used Jetpack, Kotlin Coroutines, OkHttp in your project, then Coil will be more suitable for your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f488f4de72a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/coil-vs-glide-3f488f4de72a">Coil Vs Glide</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating to Python 3: The HealthifyMe Experience. (Part 2)]]></title>
            <link>https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-2-97a53d43e37d?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/97a53d43e37d</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Manmohan Sharma]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 05:19:17 GMT</pubDate>
            <atom:updated>2020-12-16T05:17:48.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*SqVIlpLduoT66i76pDmI8Q.jpeg" /><figcaption>We moved all the fishes 😀</figcaption></figure><p>Hello and welcome back here. This is part 2 where we will explore how HealthyfyMe moved to python 3 without having downtime with ongoing development. If you missed the <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875"><strong>part-1</strong> <strong>where we explored <em>why you should move to Python 3 and rare case difference in Python 2 and Python 3 and Compatible Solutions for those.</em></strong></a></p><h3>Introduction</h3><p>We have approximately 12–15 developer backend team. This is our base project with 7–10 build release daily, having bug fixes, improvements, security fixes, new feature development etc. Our main challenge was not to stop the current development process. We had to make sure our project is compatible with Python 3.X without breaking the compatibility with Python 2.X.</p><p>Migration is not an easy task, it’s not like you change your configuration file, settings files and it will work as expected. It’s a continuous process where we have to plan, analyze, test and iterate through code base each time we migrate. We will explain each of these details here.</p><h3>Migration Strategy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*iIF5BPf3imej_eOR6i8zWA.png" /><figcaption>Migration Strategy</figcaption></figure><h4>Plan/Research</h4><p>If your application is small and can be refactored quickly, just start fresh and re-write the code using Python 3.<br>This was not the case for us. Our application is big, works on a good scale and developers are working on different parts of the code base, you’d need a functioning application at all times. We have to plan first how we are going to migrate such a large project. We listed down all the components, scripts (python scripts for staging and prod), environments, internal and external apps where we need migration.</p><p>We spent the time to understand/research on —</p><ul><li><a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Why migrate to python 3</a>.</li><li><a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Difference between Python 2 and Python 3</a>.</li><li>How the other companies migrated like <a href="https://thenewstack.io/instagram-makes-smooth-move-python-3/">Instagram</a>, <a href="https://lwn.net/Articles/758159/">Facebook</a> etc.</li><li>Take a look at the dependencies and packages you’d need to upgrade for Python 3 support.</li></ul><h4>Analyze</h4><p>Once we spent time on research and we find out some of the existing automated tools that we used for this migration.</p><ul><li><a href="https://pypi.org/project/caniusepython3/">caniusepython3</a>: This package takes in a set of dependencies and then figures out which of them are holding you up from porting to Python 3.</li><li><a href="https://docs.python.org/3.8/library/2to3.html">2to3</a>: Automated Python 2 to 3 code translation.</li><li><a href="https://six.readthedocs.io/">six</a>: Package intended to support codebases that work on both Python 2 and 3 without modification.</li><li><a href="https://python-modernize.readthedocs.io/en/latest/index.html">Python-Modernize</a>: This library is a very thin wrapper around lib2to3 to utilize it to make Python 2 code more modern with the intention of eventually porting it over to Python 3</li><li><a href="https://python-future.org/#:~:text=python%2Dfuture%20is%20the%20missing,Python%203%20with%20minimal%20overhead.">python-future:</a> It allows you to use a single, clean Python 3.x-compatible codebase to support both Python 2 and Python 3 with minimal overhead.</li></ul><p>Apart from this, we created our own wrapper for making code compatible with python 2 and python 3. That we explained in our part-1 where we mention how some feature works differently in Python 2 and Python 3 and what is the compatible solution for such cases.</p><h3>Migration Process</h3><p><strong>Isolated Git Branch</strong>:- We followed the basic software ethics of keeping each new changes in different git branch. For better understanding for each change, we create a new git branch having prefix py3- .</p><p><strong>__future__<em>’</em>s Adding:- </strong>We added require future import to each python file to make code compatible in both python version. We added from __future__ import absolute_import, division, print_function, unicode_literals based on file code require in the python file.</p><p><strong>Compatible third-party packages updated:- </strong>We are having more than 180 third party package dependencies in our project. There were packages that are compatible with both the versions like django(1.11),simplejson(3.8.1), Requests(2.22) and some packages that are not compatible like <a href="https://pypi.org/project/redis/">redis</a>, django-cacheops, django-fake-model etc. We updated package that is not compatible with both the version and created a different requirements file for python 3.</p><p><strong>Six package:- </strong>The conclusion was to use <a href="http://six.readthedocs.io/">six</a>, which is a library to make it easy to build a codebase that is valid in both in Python 2 and 3. We used six package functionalities like six.iteritems, six.moves.range, six.moves.urllib.parse.urlencode, six.moves.zip, six.with_metaclass,six.text_type, six.string_types, six.moves.urllib.request, six.viewkeys, six.StringIO,six.moves.html_parser etc.</p><p><strong>Custom compatible wrapper:- </strong>As we mention in the <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">blog part-1</a> there were still in a lot of places where we need to write our own compatible solution that can work in both python version. We created two compatible<strong> </strong>layers one for the Unittest case and other for our main codebase. We replaced the newly created method in exiting codebase. Some of the methods are like</p><pre><br>def isPY3():<br>    &quot;&quot;&quot;Check the current running version is python 3 or not.&quot;&quot;&quot;<br>    return True if _PY == 3 else False</pre><pre>def base64ify(bytes_or_str):<br>    if _PY == 3 and isinstance(bytes_or_str, str):<br>        input_bytes = bytes_or_str.encode(&#39;utf8&#39;)<br>    else:<br>        input_bytes = bytes_or_str<br>    try:<br>        output_bytes = base64.b64encode(input_bytes)<br>    except (UnicodeEncodeError, TypeError):<br>        # This happens when the input message has<br>        # non-ascii encodable characters in an unicode string<br>        # `&#39;`(ascii encodable) vs `’`(non-ascii encodable)<br>        # In this case, we first need to encode it to utf-8<br>        # and then do the base64 encoding<br>        output_bytes = base64.b64encode(input_bytes.encode(&#39;utf-8&#39;))<br>    if _PY == 3:<br>        return output_bytes.decode(&#39;ascii&#39;)<br>    else:<br>        return output_bytes</pre><pre>def py2min(input_list):<br>    &quot;&quot;&quot;Get the minimum item from list.&quot;&quot;&quot;<br>    if not input_list:<br>        raise ValueError(&#39;List should not be empty&#39;)<br>    return min(input_list) if None not in input_list else None</pre><pre>def py2_round(x, d=0):<br>    &quot;&quot;&quot;Round same as PY2 in PY3.&quot;&quot;&quot;<br>    p = 10 ** d<br>    if x &gt;= 0:<br>        return float(math.floor((x * p) + 0.5)) / p<br>    else:<br>        return float(math.ceil((x * p) - 0.5)) / p</pre><pre>def hash_512_create(value):<br>    &quot;&quot;&quot;Hash obj creation python 2 and python 3 compatibility.&quot;&quot;&quot;<br>    if isPY3():<br>        if isinstance(value, str):<br>            value = value.encode(&#39;utf-8&#39;)<br>    return hashlib.sha512(value)</pre><pre>def django_smart_bytes(value):<br>    &quot;&quot;&quot;Django smart_bytes always returns str for python 2 and python 3 compatibility.&quot;&quot;&quot;<br>    if isPY3():<br>        return smart_bytes(value).decode(&#39;utf-8&#39;)<br>    return smart_bytes(value)</pre><p>Created a wrapper for unittest case also because assertCountEqual is depricated in Py3, String to byte comparison will fail, Dict order is different in both versions, Mock lib is included in unittest lib.</p><p><strong>Unittest Case:- </strong>At HealthifyMe we always try to follow the best engineering practices. There can be a separate debate on the why we need Unittest case, but one thing we learn with this migration is that<strong> if you have Unittest case with good coverage then you will save your 30–40 % time in migration. </strong>In Healthifyme we have test coverage of more than 90%,<strong> </strong>because of which<strong> </strong>we felt comfortable changing some parts of the code since this wouldn’t cause lots of bugs on production.</p><p><strong>CICD Pipeline:- </strong>We started running two CICD pipelines for both python 2 and python 3. Here we were trying to make sure that once migrated, compatible code should not be changed in a non-compatible way.</p><p><strong>Code changes/Developers learning:- </strong>We are having more then 150 app’s in our monolith Django project. We started picking each app and try to make the code compatible with both the python version. Once the app is compatible we add that to our CICD pipeline. This way we were making sure that for the migrated app if developers are making any code change the CICD pipeline will take care of code compatibility and if any part of the code breaks in any of the versions then it is the developer’s responsibility to make it compatible. In this way, we are making sure for all the migrated app will be compatible with our new code and developer also will be familiar with how to write compatible code. Like this way, we migrated all the Django project apps.</p><h4>Are we done?</h4><p>No, We are not done. Till now we were making sure (using Unittest case) that our code is compatible with both python version but this does not mean that we are ready for python 3, but we were about 70–75% ready.</p><p><strong>Preparation for Dev testing Rollout/Manual testing:- </strong>We use <a href="https://newrelic.com/">Newrelic</a> to track the performances of application and <a href="https://sentry.io/">Sentry</a> for bug tracking. We created two configurations based on the python version and also created different <a href="https://docs.celeryproject.org/en/stable/">celery</a> queues configuration for both versions.</p><p><strong>Manual Testing bug fixes</strong>:- After this, we released our application for DEV testing with python 3 and started manual testing on this for a couple of days. We monitored the application using sentry and Newrelic. Here we found below issues:-</p><ul><li><em>Sentry bugs:</em> We faced most of the bugs related to data comparisons, string formatting and hashing related.</li><li>String formatting issue: &#39;Hello {}&#39;.format(b&#39;HealthifyMe&#39;) is &#39;Hello HealthifyMe&#39; in Python 2, but “Hello b’HealthifyMe’” in Python 3. This is silent behaviour in python 3 (I do not really agree with this: For me either its behaviour, should not change (existing code works) or it should throw an exception (would have been best!))</li><li><em>Django-redis-cache slow delete pattern</em>: Using the Newrelic we faced deleting keys were slow in <a href="https://github.com/sebleier/django-redis-cache/issues/169">django-redis-cache</a>.</li><li><em>Django model migration issue:- </em>Check-in <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Part-1 </a>Third-party library fixes Django.</li><li><em>Django admin console </em><a href="https://stackoverflow.com/questions/9336463/django-xxxxxx-object-display-customization-in-admin-action-sidebar"><em>xxxxxx display issue</em></a><em>:- </em>Check-in <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Part-1</a> Third-party library fixes Django.</li></ul><p><strong>Python pickle issue while running the application in both versions:- </strong>Now after this, we started looking code compatibility for python 2 and python 3 at the same time. Till now we were having UAT instance for both Python version. We started routing our UAT traffic in both instances we starting from 10%, eventually increasing the traffic. While we were doing this we faced Python pickle object issue, explained this in <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">blog part-1</a><br>Fix:- There is a ready fix for <a href="https://pypi.org/project/django-redis-cache/">django-redis-cache</a>where we have to specify the pickle protocol version in Django settings <a href="https://github.com/sebleier/django-redis-cache/issues/65">like</a></p><pre>CACHES = {<br>             &quot;default&quot;: {<br>                          # ...   <br>                          &quot;OPTIONS&quot;: {<br>                                 &quot;PICKLE_VERSION&quot;: -1  # Use the latest protocol version (default), for py2 compatibility use 2<br>                       }<br>             }   <br>      }</pre><p>For <a href="https://pypi.org/project/django-cacheops/">django-cacheops</a> Please check <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Part-1</a> Third-party library fixes django-cacheops package<strong>.</strong></p><p><strong>Testing with prod DB:- </strong>As we are a B2C company, handling millions of requests, so before rolling out the backend to production, we did one more round of testing. We made a prod instance in python 3 and connected with prod DB. We did manual testing on this instance by this we make sure that our code is compatible with prod data and we can run prod with both python 2 and python 3 instances at a time.</p><p><strong>Production Rollout:- </strong>Now we were ready for Prod rollout, but here also we rolled out in this manner</p><ul><li>Run all the Dev, UAT instance with equal traffic split.</li><li>Rollout less traffic machine and not business impact servers in prod with 0.01% traffic.</li><li>After one day for the Increased traffic from 0.01% to 1% then 5% then 10%.</li><li>Send full traffic for short period and fix the bugs related to string formatting and comparison related.</li><li>Rollout traffic for other service instance. (We started with sending the traffic to the less busy servers first)</li><li>In the end, when we were confident we started sending traffic to business impacted (Payment related traffic) servers with the same gradual manner.</li></ul><p>One thing we want to mention is that we didn’t face any major issue in Production and the production rollout was smooth.</p><p>After this me removed the python 2 CICD pipeline, Python 2 servers for all environments.</p><h4>Conclusion:</h4><p>Ultimately HealthifyMe moved to Python 3 without having any downtime with continues development, after that we started looking migration for Django 2.2. I hope this article will help readers to migrate to Python 3.</p><p><strong>Special Mention:-</strong> This migration was impossible without the help of HealthifyMe’s CTO <a href="https://medium.com/@therealsachin">Sachin Shenoy</a>, Team lead and DevOps <a href="https://www.linkedin.com/in/tharunreddy/">Tharun</a>(one-man army), my colleague <a href="https://medium.com/@akhilrrocks">Akhil</a> and Tech Team.</p><h4>What’s next</h4><p>Stay tuned to <a href="https://medium.com/healthify-tech">HealthifyMe tech</a> blogs guys, we have more interesting blogs to come about Django 2.2 migration, MySQL migration, and about the best practices that we follow.</p><h4>Special Notes</h4><p>We are Hiring 😀 ! It’s an exciting time to join HealthifyMe engineering team. Please have a look at <a href="https://www.healthifyme.com/careers/">HealthifyMe careers</a> page. We have a lot of exciting problems to solve in many domains like Scalability, DevOps, Backend, System design etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a53d43e37d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-2-97a53d43e37d">Migrating to Python 3: The HealthifyMe Experience. (Part 2)</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Custom Activity in UIActivityController]]></title>
            <link>https://medium.com/healthify-tech/adding-custom-activity-in-uiactivitycontroller-ed16e721ec82?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed16e721ec82</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[uiactivityviewcontroller]]></category>
            <category><![CDATA[custom-activity]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sonal Bellani]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 09:22:22 GMT</pubDate>
            <atom:updated>2020-11-18T17:20:27.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adding Custom Activity in UIActivityViewController</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*Z-NEcmUUxrM8nO3E2txeqQ.png" /></figure><p>Almost every iOS app developer knows about UIActivityViewController, in our iOS apps we often need to share content to external apps for which we use UIActivityViewController. But do you know, you can easily share content within your app through UIActivityViewController just by adding a custom activity to it. You can also add custom activity to have other functionalities as well apart from sharing such as archive content, reverse string, etc.</p><p>Basic code of UIActivityViewController:</p><pre>let text = “Share Achievement”<br>let image = UIImage(named:”shareImg”)<br>let activityC = UIActivityViewController(activityItems: [image, text], applicationActivities:nil)</pre><p>The initializer method of UIActivityViewController has two arguments named <strong>activityItems: </strong>and <strong>applicationActivities: </strong>. In the first parameter we must pass the array of items to share. Have you ever thought, what to pass inside applicationActivities in the above code?</p><p>So, this <strong>applicationActivities: </strong>is the place where we pass our custom activity. First let’s talk about how to create custom activity.</p><p>To create an application activity we subclass the <strong>UIActivity</strong> and override the methods and properties of <strong>UIActivity</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2011f1b6148377292a944c9d4d67c5/href">https://medium.com/media/8f2011f1b6148377292a944c9d4d67c5/href</a></iframe><p>To use this in <strong>UIActivityViewController</strong> pass the instance of <strong>CustomActivity</strong> to the <strong>applicationActivities</strong> parameter of the initializer method of <strong>UIActivityViewController.</strong></p><pre>let activityC = UIActivityViewController(activityItems: [image, text], applicationActivities:CustomActivity())</pre><p>Congratulations, you have created your first custom activity. That was so easy, isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*gBhBmmHp8MDu6t17ZkEwNg.png" /></figure><p>In HealthifyMe iOS app, we have used custom activity to add “HealthifyMe Groups” option which let user to share their achievements within the app in different groups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed16e721ec82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/adding-custom-activity-in-uiactivitycontroller-ed16e721ec82">Adding Custom Activity in UIActivityController</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating to Python 3: The Healthifyme Experience (Part 1)]]></title>
            <link>https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/feaecfd58875</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manmohan Sharma]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 14:40:52 GMT</pubDate>
            <atom:updated>2020-12-16T05:20:55.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating to Python 3: The HealthifyMe Experience.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OqPCmc0Mu-3l2bCBENUAA.png" /></figure><p>Hello there!, this blog is about how to do Python 3 migration of a legacy monolith project without taking any downtime. We have 2 parts for this.</p><blockquote>First Blog: This blog has information about why you should migrate to Python 3 and rare case difference in Python 2 and Python 3 and <strong>Compatible Solutions for those</strong>.</blockquote><blockquote><a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-2-97a53d43e37d">Second Blog</a>: How HealthifyMe moved to Python 3 without having downtime with ongoing development.</blockquote><h3>Introduction</h3><p>Python is the primary coding language at HealthifyMe. We are using Python 3 for all the new projects but our legacy project was still running with Python 2.7 with Django(1.11). Our monolith project is 7 years old with more than 2 million lines of python code. Some of the reasons why we moved to python 3:</p><ol><li><strong>Support dropped for python 2:</strong>After Jan 2020, support for Python 2 will not be provided.</li><li><strong>Python 3 Adoption: </strong>As most of the companies, the open-source project is already adopting Python 3. New libraries, tools, modules, frameworks will be written in Python 3. <br>The existing open-source project also migrated and new feature, fixes, security improvement are coming in Python 3.</li><li><strong>Software security: </strong>Ensuring software security is a legal requirement, especially when you’re dealing with personal information in the realm of GDPR. <strong>Keeping your software up to date understandably ranks very high among security best practices, </strong>and an outdated Python interpreter would be all but guaranteed to show up as a red flag during a security audit. Security-testing tools like Black Duck has reported many vulnerabilities, exploits, and security issues in Python 2. And most of them are fixed in the latest Python 3 versions (3.7.5, 3.8.0).</li><li><strong>Performance and new features</strong>: Python 3 has better performance than python 2.<a href="https://www.youtube.com/watch?v=66XoCk79kjM&amp;t=2346"> <strong>The new software product that uses python 3 has reported a 12 % CPU performance boost and a 30% improvement in using memory resources</strong></a><strong>.<br></strong>also, python 3 gives us: <br> * <strong>native asynchronous programming.<br> * type annotations</strong> you can use to improve static code analysis and overall usability. <br><strong>* chained exceptions</strong>, which are especially useful when debugging.<br><strong>* other helpful features</strong> that make coding in Python much more efficient.</li></ol><p>This list goes on, and it is sure to grow with each new Python 3 release.</p><p>These are some reasons for us to migrate to python 3. We have approximately 12–15 developer backend team. This is our base project with 7–10 build release daily, having bug fixes, improvement, security fixes, new feature development etc. Our main challenge was not to stop the current development process. We had to make sure our project is compatible with Python 3.X without breaking the compatibility with Python 2.X. The migration was led by 1 developer (of course, with the help of other devs).</p><p>In this article, we’ll try to illustrate all the various steps taken, problems faced, and a few more details.</p><h3>Difference between python 2 and python 3.</h3><p>We can find out the common difference here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Cy0UwoDbQYcv1bTOwVotRw.png" /></figure><blockquote><a href="https://docs.python.org/3/whatsnew/3.0.html">https://docs.python.org/3/whatsnew/3.0.html</a><br><a href="https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html">https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html</a><br><a href="https://jaxenter.com/differences-python-2-3-148432.html">https://jaxenter.com/differences-python-2-3-148432.html</a><br><a href="https://python-future.org/compatible_idioms.html">https://python-future.org/compatible_idioms.html</a></blockquote><p><strong>Now we will describe in brief some of the rare and edge cases we faced when we started our migration.</strong></p><h4><strong>Data type Comparison:</strong></h4><p>1. In Python 2 comparing an integer to none will work, such that none is considered less than an integer, even negative ones. Also, you can compare none with string, string with int . <br>Different data type comparison is not allowed in python 3.<br>This is known by most of the developer but we faced edge case where NotImplementedType was compared with int and this will not work in python 3.</p><p>Code Snippet :</p><pre>class Base(object):<br>     PHONE_NO_SIZE_LIMIT = NotImplemented</pre><pre>base = Base() <br>if base.PHONE_NO_SIZE_LIMIT &gt; 10: <br>    print(&quot;Pass correct phone number&quot;)<br>else:<br>    print(&quot;Valid phone number&quot;)</pre><p>If we save this with phone_number_validation.py and run the code:</p><pre><strong># Python 2</strong><br>mac@192 ~ % python phone_number_validation.py<br>Pass correct phone number</pre><pre><strong># Python 3</strong><br>mac@192 ~ % python3.7 phone_number_validation.py<br>Traceback (most recent call last):<br>  File &quot;phone_number_validation.py&quot;, line 4, in &lt;module&gt;<br>    if base.PHONE_NO_SIZE_LIMIT &gt; 10:<br>TypeError: &#39;&gt;&#39; not supported between instances of &#39;NotImplementedType&#39; and &#39;int&#39;</pre><p><strong>Compatible Solution:<br></strong>We have to check if base.PHONE_NO_SIZE_LIMIT is implemented or not, if not then we have to handle it. Like:</p><pre>if isinstance(base.PHONE_NO_SIZE_LIMIT, type(NotImplemented)):<br>    # Have logic here, also exit/return here.<br>    print(&quot;Phone size is not implemented&quot;)if base.PHONE_NO_SIZE_LIMIT &gt; 10:     <br>    print(&quot;Pass correct phone number&quot;)<br>else:<br>    print(&quot;Valid phone number&quot;)</pre><p>2. Min, Max Math functions:<strong><br></strong>Comparison cant’s work in int to none, int to str, none to str in python 3, so the math function min and Max also have changed in python 3.</p><pre><strong># Python 2 </strong><br>&gt;&gt;&gt; max([1, None, 2])<br> 2 <br>&gt;&gt;&gt; max([1, None, 2, &quot;abc&quot;])<br> &#39;abc&#39; <br>&gt;&gt;&gt; min([1, None, 2, &quot;abc&quot;])<br> None  </pre><pre><strong># Python 3 </strong><br>&gt;&gt;&gt; max([1, None, 2]) <br> Traceback (most recent call last):   <br>   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br> TypeError: &#39;&gt;&#39; not supported between instances of &#39;NoneType&#39; and &#39;int&#39;  </pre><pre>&gt;&gt;&gt; max([1, 2, &quot;abc&quot;, None])<br>Traceback (most recent call last):<br>   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; TypeError: &#39;&gt;&#39; not supported between instances of &#39;str&#39; and &#39;int&#39;</pre><p><strong>Compatible Solution:</strong><br> 1. The list should have data of one type either string or int <br>2. With one type if none is there we can have our own method to handle this like.</p><pre>def py2max(input_list):<br>    &quot;&quot;&quot;Get the maximum item from list.&quot;&quot;&quot;<br>    if not input_list:<br>        raise ValueError(&#39;List should not be empty&#39;)<br>    formated_input_list = [rec for rec in input_list if rec is not None]<br>    return max(formated_input_list) if formated_input_list else None</pre><h4><strong>Hex encoding/decoding</strong></h4><p>While we encode a string in python 2 if we follow this &lt;str_to_be_encoded&gt;.encode(‘hex’) This will not work in Python 3</p><pre><strong># ENCODING</strong></pre><pre><strong># Python 2</strong><br>&gt;&gt;&gt; &quot;msg_to_be_encoded&quot;.encode(&#39;hex&#39;)<br>&#39;6d73675f746f5f62655f656e636f646564&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; &quot;msg_to_be_encoded&quot;.encode(&#39;hex&#39;) <br>Traceback (most recent call last):   <br>    File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>LookupError: &#39;hex&#39; is not a text encoding; use codecs.encode() to handle arbitrary codecs</pre><pre><strong># DECODING</strong></pre><pre><strong># Python 2 </strong><br>&gt;&gt;&gt; &quot;6d73675f746f5f62655f656e636f646564&quot;.decode(&#39;hex&#39;) &#39;msg_to_be_encoded&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; b&quot;6d73675f746f5f62655f656e636f646564&quot;.decode(&#39;hex&#39;) <br>Traceback (most recent call last):   <br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>LookupError: &#39;hex&#39; is not a text encoding; use codecs.decode() to handle arbitrary codecs</pre><pre><strong># Also look at exception here in python 2  and python 3.</strong></pre><pre><strong># Python 3</strong></pre><pre>&gt;&gt;&gt; b&quot;6d73675f746f5f62655f656e636f646564&quot;.decode(&#39;hex&#39;) <br>Traceback (most recent call last):   <br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br><strong>LookupError:</strong> &#39;hex&#39; is not a text encoding; use codecs.decode() to handle arbitrary codecs</pre><pre><strong># Python 2</strong></pre><pre>&gt;&gt;&gt; &quot;6d73675f746f5f62655f656e636f64656&quot;.decode(&#39;hex&#39;) <br>Traceback (most recent call last):   <br>   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;   <br>   File       &quot;/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/hex_codec.py&quot;, line 42, in hex_decode     <br>   output = binascii.a2b_hex(input) <br><strong>TypeError:</strong> Odd-length string</pre><p><strong>Compatible Solution:<br></strong>We should use codecs for Python 3 and 2. In python 3 input and output both is byte datatype.</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; import codecs<br>&gt;&gt;&gt; message = &quot;msg_to_be_encoded&quot;<br>&gt;&gt;&gt; codecs.encode(message.encode(), &#39;hex&#39;)<br>&#39;6d73675f746f5f62655f656e636f646564&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; message = &quot;msg_to_be_encoded&quot;<br>&gt;&gt;&gt; codecs.encode(message.encode(), &#39;hex&#39;)<br>b&#39;6d73675f746f5f62655f656e636f646564&#39;</pre><h4><strong>String uppercase:</strong></h4><p>string.uppercase doesn’t work in python 3.</p><pre><strong># Python 2 </strong><br>&gt;&gt;&gt; import string <br>&gt;&gt;&gt; string.uppercase <br>&#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;</pre><pre><strong># Python 3 </strong><br>&gt;&gt;&gt; import string <br>&gt;&gt;&gt; string.uppercase <br>Traceback (most recent call last):   <br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; <br>AttributeError: module &#39;string&#39; has no attribute &#39;uppercase&#39;</pre><p><strong>Compatible Solution:<br> </strong>Use<strong> </strong>ascii_uppercase</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; import string<br>&gt;&gt;&gt; string.ascii_uppercase<br>&#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; import string<br>&gt;&gt;&gt; string.ascii_uppercase<br>&#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;</pre><h4><strong>hasattr():</strong></h4><p>hasattr() presents a huge edge case when writing Python 2 and 3 compatible code.hasattr() checks for the existence of an attribute by trying to retrieve it.</p><p><strong>Python 2</strong></p><blockquote><strong>hasattr</strong>(<em>object</em>, <em>name</em>)<br>The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)</blockquote><p><strong>Python 3</strong></p><blockquote><strong>hasattr</strong>(<em>object</em>, <em>name</em>)The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an <a href="https://docs.python.org/3/library/exceptions.html#AttributeError">AttributeError</a> or not.)</blockquote><p>Please find more details here: <a href="https://medium.com/@k.wahome/python-2-vs-3-hasattr-behaviour-f1bed48b068">https://medium.com/@k.wahome/python-2-vs-3-hasattr-behaviour-f1bed48b068</a></p><p><strong>Sample code</strong></p><pre>class Foo(dict):     <br>    def __init__(self):         <br>        super(Foo, self).__init__()         <br>        self.example_dict = {}  <br>    <br>    def __getitem__(self, key):         <br>        try:             <br>            return super(Foo, self).__getitem__(key)<br>        except KeyError:<br>            return self.example_dict[key]</pre><pre>    def __getattr__(self, key):<br>        return self[key]</pre><pre>foo = Foo() <br>if hasattr(foo, &quot;not_present_key&quot;):<br>    pass  <br>else:     <br>    print(&quot;Not Found&quot;)</pre><p>Save the above snippet with hasattr_test.py</p><pre><strong># Python 2</strong></pre><pre>mac@192 ~ % python hasattr_test.py <br>Not Found</pre><pre><strong># Python 3</strong></pre><pre>mac@192 ~ % python3.7 hasattr_test.py<br>Traceback (most recent call last):<br>  File &quot;hasattr_test.py&quot;, line 8, in __getitem__<br>    return super(Foo, self).__getitem__(key)<br>KeyError: &#39;not_present_key&#39;</pre><pre>During handling of the above exception, another exception occurred:</pre><pre>Traceback (most recent call last):<br>  File &quot;hasattr_test.py&quot;, line 17, in &lt;module&gt;<br>    if hasattr(foo, &quot;not_present_key&quot;):<br>  File &quot;hasattr_test.py&quot;, line 13, in __getattr__<br>    return self[key]<br>  File &quot;hasattr_test.py&quot;, line 10, in __getitem__<br>    return self.example_dict[key]<br>KeyError: &#39;not_present_key&#39;</pre><p><strong>Compatible Solution:<br> </strong>To make code compatibility in Python 2 and Python 3, we have to change __getattr__ function like below.</p><pre>def __getattr__(self, key):<br>    try:<br>        return self[key]<br>    except KeyError:<br>       raise AttributeError</pre><h4><strong>Dict becomes ordered in python 3:</strong></h4><p>From Python 3.6+ onwards dictionary is now default <strong>insertion ordered</strong>.</p><pre># Python 2<br> &gt;&gt;&gt; sample_dict = {}<br> &gt;&gt;&gt; sample_dict[&quot;a&quot;] = 1<br> &gt;&gt;&gt; sample_dict[&quot;b&quot;] = 2<br> &gt;&gt;&gt; sample_dict[&quot;c&quot;] = 3<br> &gt;&gt;&gt; sample_dict[&quot;d&quot;] = 4<br> &gt;&gt;&gt; sample_dict<br> {&#39;a&#39;: 1, &#39;c&#39;: 3, &#39;b&#39;: 2, &#39;d&#39;: 4}</pre><pre># Python 3<br> &gt;&gt;&gt; sample_dict = {}<br> &gt;&gt;&gt; sample_dict[&quot;a&quot;] = 1<br> &gt;&gt;&gt; sample_dict[&quot;b&quot;] = 2<br> &gt;&gt;&gt; sample_dict[&quot;c&quot;] = 3<br> &gt;&gt;&gt; sample_dict[&quot;d&quot;] = 4<br> &gt;&gt;&gt; sample_dict<br> {&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3, &#39;d&#39;: 4}</pre><p><strong>Compatible code:<br> </strong>Ideally, this should not break the application code, because it changed to unordered to ordered dict. If still, we need the same result in both python version (order is important, test case failing) we have to use OrderedDict for keeping both language output the same.</p><h4><strong>Hashing:</strong></h4><p>In python 2 input can be typed unicode and str , but in Python 3 it needs bytes</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; import hashlib<br>&gt;&gt;&gt; message = &quot;healthify&quot;<br>&gt;&gt;&gt; hashlib.sha512(message).hexdigest().lower()   <br>&#39;f910c1fa68087a546512ac3b175c99ee7eba21360fa4e579c2aed649c7e4a43466c56bceedcd60d783bc6e7d069a16f0b9c67140d6c129d2a1898af8cfb62719&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; message = &quot;healthify&quot;<br>&gt;&gt;&gt; hashlib.sha512(message).hexdigest().lower()<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>TypeError: Unicode-objects must be encoded before hashing</pre><p><strong>Compatible Solution:<br> </strong>Python 3 needs bytes as input, where python 2 works with type unicode and str both.</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; import hashlib<br>&gt;&gt;&gt; message = &quot;healthify&quot;<br>&gt;&gt;&gt; hashlib.sha512(message.encode(&#39;utf-8&#39;)).hexdigest().lower()   <br>&#39;f910c1fa68087a546512ac3b175c99ee7eba21360fa4e579c2aed649c7e4a43466c56bceedcd60d783bc6e7d069a16f0b9c67140d6c129d2a1898af8cfb62719&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; message = &quot;healthify&quot;<br>&gt;&gt;&gt; hashlib.sha512(message.encode(&#39;utf-8&#39;)).hexdigest().lower()<br>&#39;f910c1fa68087a546512ac3b175c99ee7eba21360fa4e579c2aed649c7e4a43466c56bceedcd60d783bc6e7d069a16f0b9c67140d6c129d2a1898af8cfb62719&#39;</pre><h4><strong>__div__ operator overloading:</strong></h4><p>In python 3, the __div__ operator seems not to exist as it was replaced by __truediv__ entirely.</p><pre>class item:<br>    fats = 0.0<br>    <br>   def __div__(self, other):<br>        self.fats = self.fats / other</pre><pre>it = item()<br>it.fats = 34.0<br>it / 3<br>print(it.fats)</pre><pre># python 2 output<br>11.3333333333</pre><pre># Python 3 output <br>Traceback (most recent call last):<br>  File &quot;div_overloading.py&quot;, line 16, in &lt;module&gt;<br>    print(AB / 3)<br>TypeError: unsupported operand type(s) for /: &#39;Vector2&#39; and &#39;int&#39;</pre><p><strong>Compatible Solution:<br> </strong>In Python 3.x, we have to overload the __truediv__ operators, not the __div__ operator. For making code compatible, we have to keep both methods like:</p><pre>class item:<br>    fats = 0.0</pre><pre>    def __div__(self, other):<br>        self.fats = self.fats / other<br>  <br>   def __truediv__(self, other):<br>        self.fats = self.fats / other</pre><pre>it = item()<br>it.fats = 34.0<br>it / 3<br>print(it.fats)</pre><pre># python 2 output<br>11.3333333333</pre><pre># Python 3 output <br>11.333333333333334</pre><h4><strong>Base64 encoding:</strong></h4><p>We do the base64 encoding using base64.b64encode(&lt;string_to_be_encode&gt;). In Python 2 we can pass unicode or str as input. But in python 3 it needs the bytes as input.</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; from base64 import b64encode<br>&gt;&gt;&gt; b64encode(&quot;man&quot;)<br>&#39;bWFu&#39;<br>&gt;&gt;&gt; b64encode(u&quot;man&quot;)<br>&#39;bWFu&#39;</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; from base64 import b64encode<br>&gt;&gt;&gt; b64encode(&quot;man&quot;)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>  File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/base64.py&quot;, line 58, in b64encode<br>    encoded = binascii.b2a_base64(s, newline=False)<br>TypeError: a bytes-like object is required, not &#39;str&#39;<br></pre><p><strong>Compatible Solution:<br> </strong>We can have our own method for base64 encoding and it can have input string and bytes both.</p><pre>import base64<br>import six<br>def base64ify(bytes_or_str):<br>    if six.PY3 and isinstance(bytes_or_str, str):<br>        input_bytes = bytes_or_str.encode(&#39;utf8&#39;)<br>    else:<br>        input_bytes = bytes_or_str<br>    try:<br>        output_bytes = base64.b64encode(input_bytes)<br>    except (UnicodeEncodeError, TypeError):<br>        # This happens when the input message has<br>        # non-ascii encodable characters in an unicode string<br>        # `&#39;`(ascii encodable) vs `’`(non-ascii encodable)<br>        # In this case, we first need to encode it to utf-8<br>        # and then do the base64 encoding<br>        output_bytes = base64.b64encode(input_bytes.encode(&#39;utf-8&#39;))<br>    if six.PY3:<br>        return output_bytes.decode(&#39;ascii&#39;)<br>    else:<br>        return output_bytes</pre><h4><strong>Inbuilt round method:</strong></h4><p><strong>Python2</strong>: Rounding is done <strong>away from </strong>(so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0)<br><strong>Python 3</strong>: Rounding is done <strong>toward the even choice</strong> (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; round(15.5)<br>16.0<br>&gt;&gt;&gt; round(16.5)<br>17.0</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; round(15.5)<br>16<br>&gt;&gt;&gt; round(16.5)<br>16</pre><p><strong>Compatible Solution:<br> </strong>We created our own round method that works the same as Python 2 round in python 3 also.</p><pre>def py2_round(x, d=0):<br>    &quot;&quot;&quot;Round same as PY2 in PY3.&quot;&quot;&quot;<br>    p = 10 ** d<br>    if x &gt;= 0:<br>        return float(math.floor((x * p) + 0.5)) / p<br>    else:<br>        return float(math.ceil((x * p) - 0.5)) / p</pre><h4><strong>struct.pack input type:</strong></h4><p>input type is str , Python 3 it should be byte</p><pre># Python 2<br>&gt;&gt;&gt; import struct<br>&gt;&gt;&gt; import struct<br>&gt;&gt;&gt; string = &quot;blab&quot;<br>&gt;&gt;&gt; s = struct.Struct(b&#39;4s&#39;)<br>&gt;&gt;&gt; packed_data = s.pack(string)</pre><pre># Python 3<br>&gt;&gt;&gt; import struct<br>&gt;&gt;&gt; string = &quot;blab&quot;<br>&gt;&gt;&gt; s = struct.Struct(b&#39;4s&#39;)<br>&gt;&gt;&gt; packed_data = s.pack(string)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>struct.error: argument for &#39;s&#39; must be a bytes object</pre><p><strong>Compatible Solution: <br> </strong>encode the input<strong>.</strong></p><h4><strong>list comprehension variable </strong><strong>scope changes:</strong></h4><p>In Python 3 the list comprehension variable use enclosing scope mean you will not able to access the plan variable outside in the function, this was not the case in Python 2.</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; def two_or_three():<br>...     x = 3<br>...     [0 for x in range(3)]<br>...     return x<br>...<br>&gt;&gt;&gt; two_or_three()<br>2</pre><pre>&gt;&gt;&gt; def two_or_three_with_method():<br>...     def print_number():<br>...             print(x)<br>...     [0 for x in range(3)]<br>...     print_number()<br>...<br>&gt;&gt;&gt; two_or_three_with_method()<br>2</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; def two_or_three():<br>...     x = 3<br>...     [0 for x in range(3)]<br>...     return x<br>...<br>&gt;&gt;&gt; two_or_three()<br>3</pre><pre>&gt;&gt;&gt; def two_or_three_with_method():<br>...     def print_number():<br>...             print(x)<br>...     [0 for x in range(3)]<br>...     print_number()<br>...<br>&gt;&gt;&gt; two_or_three_with_method()<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>  File &quot;&lt;stdin&gt;&quot;, line 5, in two_or_three<br>  File &quot;&lt;stdin&gt;&quot;, line 3, in print_number<br>NameError: name &#39;x&#39; is not defined</pre><p><strong>Compatible Solution: <br> </strong>We should avoid such cases. For the second method (two_or_three_with_method ) we have to pass x value as an argument.</p><h4><strong>math.floor and math.ceil return data type changed:</strong></h4><p>In python 2 the floor and ceil return float data type but in python 3 it returns int data type.</p><pre><strong># Python 2</strong><br>&gt;&gt;&gt; from math import floor,ceil<br>&gt;&gt;&gt; floor(4.345)<br>4.0<br>&gt;&gt;&gt; ceil(4.345)<br>5.0</pre><pre><strong># Python 3</strong><br>&gt;&gt;&gt; from math import floor,ceil<br>&gt;&gt;&gt; floor(4.345)<br>4<br>&gt;&gt;&gt; ceil(4.345)<br>5</pre><p><strong>Compatible Solution: <br> </strong>We can make the output as a float in python 3. It will not impact python 2, <strong>float(floor(4.345))</strong></p><h4><strong>Unpickling a python 2 pickled object into python 3:</strong></h4><p>As mention, we are making code compatible to run both python version. we faced an issue while the object is pickled in Python 2 but we are not able to unpickle in python 3. This can happen for Redis Pickled cached objects also.</p><p>pickle.load(), default is to try and decode all string data as ASCII, and that decoding fails. See the <a href="https://docs.python.org/3/library/pickle.html#pickle.load">pickle.load() documentation</a>:</p><blockquote>Optional keyword arguments are <em>fix_imports</em>, <em>encoding</em> and <em>errors</em>, which are used to control compatibility support for pickle stream generated by Python 2. If <em>fix_imports</em> is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The <em>encoding</em> and <em>errors</em> tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The <em>encoding</em> can be ‘bytes’ to read these 8-bit string instances as bytes objects.</blockquote><p><a href="https://stackoverflow.com/questions/28218466/unpickling-a-python-2-object-with-python-3">https://stackoverflow.com/questions/28218466/unpickling-a-python-2-object-with-python-3</a></p><p><strong>Compatible Solution: <br> </strong>We can use the below method to unpickle objects.</p><pre>def unpickling_py2_to_py3(pickled_value):<br>    &quot;&quot;&quot;Unpickling python 2 pickled in to python 3.&quot;&quot;&quot;<br>    if isPY3():<br>        try:<br>            value = pickle.loads(pickled_value)<br>        except UnicodeDecodeError:<br>            value = pickle.loads(pickled_value, encoding=&quot;latin1&quot;)<br>    else:<br>        value = pickle.loads(pickled_value)<br>    return value</pre><h4><strong>Third-party library fixes:</strong></h4><p>In our Project we are using a lot of third party packages, while we update them we faced some edge cases. You can skip this if you are not using any of them.</p><ol><li><a href="https://github.com/django/django"><strong>Django</strong></a><strong>:</strong> <br><strong>a. Django migration files</strong><br> When we run Django makemigrations in python 3 we were seeing new migration files. but the same was not happening for python 2. There can be multiple reasons for this.</li></ol><blockquote><strong>b prefix: </strong>On makemigration most of the new files are generated without having b prefix for string values.This is because all string literals used in your models and fields (e.g. ``verbose_name``,``related_name``, etc.), must be consistently either byte strings or text(unicode) strings in both Python 2 and 3.</blockquote><blockquote><strong>Compatible Solution: </strong>The easiest way to achieve one migration for new migration add from __future__ import unicode_literal to all models files. For existing migration files either we run makemigration and that should only happen once, or we can remove b prefix from existing migration files.</blockquote><blockquote><strong>Choice Field: </strong>In models we use dict.items(). As we know now that the <strong>dict become ordered in python 3</strong> so the values return from dict.items() will be differ in Python 2 and Python 3.</blockquote><blockquote><strong>Compatible Solution: </strong>To make compatible for both we sorted(dict.items()) and generated migration file that is now compatible for both python versions.</blockquote><p><strong>b. “&lt;model_name&gt; Object” display in admin console<br></strong>For python 3 in Admin console, we can see &lt;model_name&gt; Object as fields value instead of a string.<strong> </strong>if was happening because our model class having method.</p><pre>def __unicode__(self):<br>    return &#39;MyModel: {}&#39;.format(self.name)</pre><p>We can have str method __str__ and that works for both Python 2and Python 3. But it will fail if the str version has non-ASCII characters.</p><p><strong>Compatible Solution: </strong>Got the solution from <a href="https://docs.djangoproject.com/en/1.11/topics/python3/#str-and-unicode-methods">here</a>, added @python_2_unicode_compatible decorator for models and modified __unicode__ to __str__ .</p><p><strong>c. Django query object slicing</strong><br> Django query object has slicing capability to fetch records. for Django version(1.11), python 2 it supports slicing for int and str. In Python 3 it only supports slicing through the int.</p><pre># Python 2<br>&gt;&gt;&gt; from food import models<br>&gt;&gt;&gt; foods = models.foods.objects.all()<br>&gt;&gt;&gt; foods[1:2] # int slicing<br>&lt;QuerySet [&lt;Foods: Cashewnut Cutlets  &gt;]&gt;<br>&gt;&gt;&gt; foods[&quot;1&quot;:&quot;2&quot;] # string slicing<br>&lt;QuerySet [&lt;Foods: Cashewnut Cutlets  &gt;]&gt;</pre><pre># Python 3<br>In [2]: from food import models<br>In [3]: foods = models.Foods.objects.all()<br>In [4]: foods[&quot;1&quot;:&quot;2&quot;]<br>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>&lt;ipython-input-4-be74a70cdff4&gt; in &lt;module&gt;<br>----&gt; 1 foods[&quot;1&quot;:&quot;2&quot;]</pre><pre>~/Venvs/py3_venv/lib/python3.7/site-packages/django/db/models/query.py in __getitem__(self, k)<br>    265             raise TypeError<br>    266         assert ((not isinstance(k, slice) and (k &gt;= 0)) or<br>--&gt; 267                 (isinstance(k, slice) and (k.start is None or k.start &gt;= 0) and<br>    268                  (k.stop is None or k.stop &gt;= 0))), \<br>    269             &quot;Negative indexing is not supported.&quot;</pre><pre>TypeError: &#39;&gt;=&#39; not supported between instances of &#39;str&#39; and &#39;int&#39;</pre><pre>In [5]: foods[1:2]<br>Out[5]: &lt;QuerySet [&lt;Foods: Foods object&gt;]&gt;</pre><p><strong>Compatible Solution: </strong>Avoid string slicing that is anyway not a good approach.</p><p>2. <a href="https://pypi.org/project/redis/"><strong>Redis</strong></a>: Redis is common used python package. redis-py 3.0 introduces many new features but required several backwards-incompatible changes to be made in the process.</p><p><strong>Compatible Solution: <br> </strong><a href="https://pypi.org/project/redis/">https://pypi.org/project/redis/</a> from here we can find out the changes and how to make compatible code. We made our own Redis methods that compatible with both Redis versions. Like</p><pre>import six<br>def redis_zadd(redis_connection, key, **values):<br>    &quot;&quot;&quot;Redis method zadd for python 2 and python 3 compatibility.&quot;&quot;&quot;<br>    if six.PY3:<br>        redis_connection.zadd(key, values)<br>    else:<br>        redis_connection.zadd(key, **values)</pre><pre>def redis_zincrby(redis_connection, key, value, score):<br>    &quot;&quot;&quot;Redis method zincrby for python 2 and python 3 compatibility.&quot;&quot;&quot;<br>    if six.PY3:<br>        redis_connection.zincrby(key, score, value)<br>    else:<br>        redis_connection.zincrby(key, value, score)</pre><p>3. <a href="https://github.com/Suor/django-cacheops"><strong>django-cacheops</strong></a>: Cacheops is a slick app that supports automatic or manual queryset caching and automatic granular event-driven invalidation. There is a gotcha while Django cacheops store values to Redis it makes them a pickle object.</p><blockquote><em>In python 2 there are 3 different protocols (0, 1, 2) and the default is 0.In python 3 there are 5 different protocols (0, 1, 2, 3, 4) and the default is 3.</em></blockquote><blockquote>Pickle use the default pickle protocol to dumps data.So in python 3 if we make a pickle object and want to unpickle in Python 2 will not work because pickle protocol 3 is not available in python 2.</blockquote><p><strong>Compatible Solution:<br> </strong><a href="https://stackoverflow.com/questions/25843698/valueerror-unsupported-pickle-protocol-3-python2-pickle-can-not-load-the-file"><strong>We can specify the protocol parameter when invoking pickle.dump.</strong></a><strong><br></strong>django-cacheops don’t have an option to provide the pickle protocol. We used monkey patching to sort out this.</p><pre>import cacheops<br>from cacheops.cross import pickle</pre><pre><a href="http://twitter.com/cacheops">@cacheops</a>.redis.handle_connection_failure<br>def <a href="https://github.com/Suor/django-cacheops/blob/3.2/cacheops/simple.py#L92">_custom_cacheops_redis_set</a>(self, cache_key, data, timeout=None):<br>    pickled_data = pickle.dumps(data, 2) # Protocol 2 is valid in both Python version.<br>    if timeout is not None:<br>        self.conn.setex(cache_key, timeout, pickled_data)<br>    else:<br>        self.conn.set(cache_key, pickled_data)</pre><pre>cacheops.RedisCache.set = _custom_cacheops_redis_set</pre><p>Also as mention above how to <strong>Unpickle a python 2 pickled object into python 3</strong>. We want to get data in python 3, <a href="https://stackoverflow.com/questions/28218466/unpickling-a-python-2-object-with-python-3">we can face UnicodeDecodeError due to picking done in different python versions.</a><br>this is also sorted using patching</p><pre>import six<br>from cacheops.simple import CacheMiss<br>if six.PY3:<br>    import pickle<br>else:<br>    import cPickle as pickle</pre><pre>def unpickling_py2_to_py3(pickled_value):<br>    &quot;&quot;&quot;Unpickling python 2 pickled in to python 3.&quot;&quot;&quot;<br>    if six.PY3:<br>        try:<br>            value = pickle.loads(pickled_value)<br>        except UnicodeDecodeError:<br>            value = pickle.loads(pickled_value, encoding=&quot;latin1&quot;)<br>    else:<br>        value = pickle.loads(pickled_value)<br>    return value</pre><pre>def <a href="https://github.com/Suor/django-cacheops/blob/3.2/cacheops/simple.py#L85">_custom_cacheops_redis_get</a>(self, cache_key):<br>    data = self.conn.get(cache_key)<br>    if data is None:<br>        raise CacheMiss<br>    return unpickling_py2_to_py3(data)</pre><pre>cacheops.RedisCache.get = _custom_cacheops_redis_get</pre><p>4. <a href="https://github.com/sebleier/django-redis-cache"><strong>django-redis-cache</strong></a>: we have a method for deleting keys based on the pattern. In Python 2 we use the version <a href="https://github.com/sebleier/django-redis-cache/blob/1.6.4/redis_cache/backends/base.py#L384">1.6.5</a> the key searching/delete was happening without scan and but for python 3 we updated the version to <a href="https://github.com/sebleier/django-redis-cache/blob/1.6.4/redis_cache/backends/base.py#L384">2.1</a> where the pattern search happening using Redis scan, that is making it so slow. This was causing the problem. <a href="https://github.com/sebleier/django-redis-cache/issues/169">Git hub issue for this</a>.</p><p><strong>Compatible Solution:<br> </strong>We sorted the issue using the old way of pattern delete. instead of calling cache.delete_pattern(pattern) we are doing</p><pre>pattern = cache.make_key(pattern)<br>keys = cache.master_client.keys(pattern)<br>if len(keys):<br>   cache.master_client.delete(*keys)</pre><h3>What’s Next</h3><p>In <a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-2-97a53d43e37d">part two</a> of this blog,<strong> </strong>where we will explore how to move to python 3 without having downtime with ongoing development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feaecfd58875" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/migrating-to-python-3-the-healthifyme-experience-part-1-feaecfd58875">Migrating to Python 3: The Healthifyme Experience (Part 1)</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Mayans’ Lost Guide To Doing Data Science In Fast Paced Startups]]></title>
            <link>https://medium.com/healthify-tech/the-mayans-lost-guide-to-doing-data-science-in-fast-paced-startups-2531128aecd0?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/2531128aecd0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 10:34:51 GMT</pubDate>
            <atom:updated>2020-09-12T16:18:33.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ccw6qjBUeyIhOzLRjUwSRw.jpeg" /></figure><blockquote><em>A machine learning model is useful only if it’s put to production at the right time.</em></blockquote><blockquote><em>No kidding!</em></blockquote><p>The quest is what are those key practices left unsaid while working in a fast and highly chaotic environment? Are the AI foundations and computer science degrees enough to make scalable models in real life? It’s not as easy as eating cotton candy.</p><p>Driven by intellectual progress, I decided to do a review of my past experience in working with Machine Learning and Deep Learning models. In this article, I’ll be using my work experience on one of my recent projects where the aim was to predict a user’s purchasing probability for our various offerings. The purpose of this project was to help the Performance Marketing and Growth Team at HealthifyMe to evaluate their efficacy and efficiency of our sales engines respectively. I am sharing below the insights I’ve had from the same on what one needs to strive towards while solving data problems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30mhXAVP9cKsVSE3XHwW0g.jpeg" /></figure><ol><li><strong>Writing a code that’s modular and reusable.</strong> Data cleaning and preprocessing does take up more than half the time of a modeling journey. Redundant work can be greatly reduced and debugging made easier on writing generic parameterized functions. <br>We, in HealthifyMe, created many generic public transformers for this which made further iterations of the model quicker and more simple. And the best outcome: they can be reused for any standard data modeling in the future!</li><li><strong>Writing both unit and integration tests (so what if it’s an AI model?).</strong> This is a vital practice especially when the code is scattered in various modules and has to go through constant iterations. A single module might work but fail when combined with data pipelines.</li><li><strong>Gradually iterating the model.</strong> It is best to add one set of features after another instead of throwing all the features in it at once, expecting the model to do the magic. Gradual iterations give a greater understanding of feature importances. Releasing small models iteratively would also keep the stakeholder’s boat moving.<br>At HealthifyMe, we decided to launch the initial version of our current model two months prior to the New Year 2020, the peak period for business, rather than waiting on its perfection, which would have come with a great opportunity cost.</li><li><strong>Documenting the tiniest bit of progress.</strong> The more attention given to details, the better. Sounds like a boring chore, but it helps tremendously while working on complex projects that involve too many moving pieces and uncertainties.<br>Among us, this made all interactions with the data engineering team super smooth and efficient. In retrospection, I feel getting them more involved in the initial stages of the journey would have actually helped us as it would have given us an understanding of their concerns.</li><li><strong>Behaving like an owner.</strong> You, and only you know where things could get really messed up. Take up responsibility and make sure that the business stakeholders, data engineers, and all other teams associated are in the loop throughout the process so that the work cycle remains unaffected. Business stakeholders may get frustrated real quick in the face of ambiguities.<br>Our team in HealthifyMe, scheduled regular brainstorming sessions with the stakeholders. This was really valuable as it helped in maintaining the morale and the exchange of quick feedback. It also helped in planning their sprints/timelines better. This was a great lesson in managing the unknowns. Planning is a great life skill to have when your games are not so finite!</li><li><strong>Making sure that the retaining mechanism and model evaluation processes are automated.</strong> (Even if it comes to extending the development phase in your sprints). The complete cycle of Data pulling + Retraining the model + Evaluating the iteration + Pushing to production, should not require another data scientist reworking on it from scratch.<br>We were quick to learn from our mistakes when we realized how much of our engineering bandwidth was spent on just trying to crack the processes involved in the previous model.</li><li><strong>A/B testing on the previous and new models.</strong> This is again a vital step in understanding delta improvement. It’s a good practice to compare each feature to judge the efficacy of the latest model. Building data algorithms is a serious mental investment with a lot of uncertainties in terms of results. Hence it is psychologically rewarding for data scientists to witness the potential impact.</li><li><strong>Keeping the model updated. </strong>Models deprecate with time in an environment where the business needs are rapidly changing. Product/strategic changes are frequent and inconsistent as we continuously strive to keep the user experience the top priority.<br>In dealing with the same, we created monitors and alerts to keep an eye on when the relevancy of the model falls and would need tweaking/revisiting in the complete approach.</li><li><strong>Being super conscious of the timeline. </strong>This is extremely important to projects that have the potential to paralyze you due to over-analysis. Even if all the steps are crystal clear in your head — it’s wise to give a 2X timeline of what you think should be the actual timeline.<br>We made the mistake of giving 0.5X and ended up taking 2X of the actual time it should have taken in an ideal scenario. An exemplar bad way of managing the expectations of the teams involved. It’s always the smartest decision to give timelines for each iteration to avoid surprises.</li><li><strong>Keeping up the partnership with stakeholders.</strong> A proactive expectations management with stakeholders plays a pivotal role in an organization’s data projects. This point cannot be stressed enough and needs to be at the forefront in every stage of the work. It should be one of the KPIs for a Data scientist to be able to do stakeholder management efficiently and educate them on how to use insights from the model in making decisions in different strategic scenarios, at the same time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z20hHzYxEBEES3nDzy92Gg.jpeg" /></figure><p><strong><em>Saurav Agarwal</em></strong><em>, Senior Data Scientist at HealthifyMe published this blog in hopes to make any organization that strives with its product, engineering, and data teams, understand the underlying intricacies and effective ways to solve them while pursuing their data strategies.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2531128aecd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/the-mayans-lost-guide-to-doing-data-science-in-fast-paced-startups-2531128aecd0">The Mayans’ Lost Guide To Doing Data Science In Fast Paced Startups</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation Component, Designing Navigation graph]]></title>
            <link>https://medium.com/healthify-tech/navigation-component-designing-navigation-graph-6db444084ddd?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/6db444084ddd</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[navigation-graph]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Karishma Agrawal]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 07:13:43 GMT</pubDate>
            <atom:updated>2020-09-09T07:13:20.976Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I would like to bring to you Nested graph and a discussion on how to pass data between two destinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gWV5YTvHfvUfGMdt.png" /></figure><h3>Nested Navigation graph</h3><p>A navigation graph can be used to group a series of destinations together and reuse them. For example, you use a view that can be used at multiple places in your application. So, you create a separate layout file and just include that wherever you want to reuse it. The same goes for the nav graph. A common flow can be included at multiple places by separating it in a diff XML file.</p><p><strong>Explaining with an example: The Custom Meal</strong></p><p>The feature of the Custom Meal in the Healthify app would help the user create meal combos. If a user likes fruits and toast for breakfast, he doesn’t have to add both, each and every day. He could create a combo meal of these two items and check the specific combo. This is a huge plus in time-saving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*tfqzlZbKyAWUcSOcIOAsQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*KZTK40yCIVMzsMSez0Xb2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*tBM11Cvo40X6FlidQvpT-g.png" /><figcaption>Custom meal flow @<a href="https://medium.com/@eyepoppper">eyepoppper</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*J2nxC3vZqs2sF1dUc5E7ng.png" /></figure><p>Shown above is the Custom meal flow; the user can name his meal and add the items in his meal to create the combo. If the simple dish is not available, he can add the ingredients.</p><p>The add button would take the user to a search screen and the searched food can be added in the list, and finally, store it by clicking on the save button, and the user will see a success screen and then we move back to the screen from where this flow started.</p><p>Let’s create a Navigation graph for Create combo flow.</p><pre><strong>&lt;!-- create_meal_graph.xml --&gt;</strong><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;navigation xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/create_meal_graph&quot;<strong><br>    </strong>app:startDestination=&quot;@id/createMealFragment&quot;&gt;<br>    &lt;fragment<br>        android:id=&quot;@+id/createMealFragment&quot;<br>        android:name=&quot;com.example.healthify.CreateMealFragment&quot;<br>        android:label=&quot;fragment_create_meal&quot;<br>        tools:layout=&quot;@layout/fragment_create_meal&quot; &gt;<br>        &lt;action<br>            android:id=&quot;@+id/action_createMealFragment_to_save&quot;<br>            app:destination=&quot;@id/processMealFragment&quot; /&gt;</pre><pre>&lt;action<br>            android:id=&quot;@+id/action_createMealFragment_to_add&quot;<br>            app:destination=&quot;@id/searchFoodFragment&quot; /&gt;<br>    &lt;/fragment&gt;</pre><pre>&lt;fragment<br>        android:id=&quot;@+id/searchFoodFragment&quot;<br>        android:name=&quot;com.example.healthify.SearchFoodFragment&quot;<br>        android:label=&quot;search_food&quot;<br>        tools:layout=&quot;@layout/fragment_search_food&quot;/&gt;<br>    <br>     &lt;fragment<br>            android:id=&quot;@+id/processMealFragment&quot;<br>            android:name=&quot;com.example.healthify.ProcessMealFragment&quot;<br>            android:label=&quot;done&quot;<br>            tools:layout=&quot;@layout/fragment_process_meal&quot;/&gt;<br>&lt;/navigation&gt;</pre><p>So here we have CreateMealFragment with 2 actions:</p><ol><li>action_createMealFragment_to_save -&gt; when the user clicks on save after entering meal name and ingredients, he will move toProcessMealFragment So destination for that action is processMealFragment .</li><li>action_createMealFragment_to_add -&gt; When the user clicks on the plus icon to add more ingredients in the combo we move to the search screen where you can search for food and add it, so the destination for this action is searchFoodFragment .</li></ol><p>This flow has 3 diff hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*NXYAvkvUnxXLarTO-gBIdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*yDVmC64uvZqpxxD_fiYYPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*roGw3XqKKtuSBayo0AIXwA.png" /><figcaption>Create meal hooks <a href="https://medium.com/u/a0b0bb07cec4">Shivangi Chowdhry</a></figcaption></figure><p>A User can enter into this flow by clicking the CREATE COMBO button on the meal tracker screen (fig 1) or CREATE A COMBO button from the Meal combo screen(fig 2) or the ADD FOOD button in the search flow(fig 3).</p><p><strong>HOOK 1</strong>: Meal tracker screen</p><pre>&lt;!-- meal_tracker_graph.xml --&gt;<br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;navigation xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/meal_tracker_graph&quot;<br>    app:startDestination=&quot;@id/mealTrackerFragment&quot;&gt;</pre><pre>&lt;include app:graph=&quot;@navigation/create_meal_graph&quot; /&gt;</pre><pre>&lt;fragment<br>        android:id=&quot;@+id/mealTrackerFragment&quot;<br>        android:name=&quot;com.example.healthify.MealTrackerFragment&quot;<br>        android:label=&quot;MealTrackerFragment&quot;<br>        tools:layout=&quot;@layout/fragment_meal_tracker&quot;&gt;<br>        &lt;action<br>            android:id=&quot;@+id/action_merge_flow&quot;<br>            app:destination=&quot;@id/create_meal_graph&quot; /&gt;<br>    &lt;/fragment&gt;</pre><pre>...<br>&lt;/navigation&gt;</pre><p>Here we have MealTrackerFragment and we have included create a meal graph. On click of CREATE COMBO button user will enter in create meal flow.</p><pre>button.setOnClickListener{<br> Navigation.findNavController(view).navigate(R.id.action_merge_flow)<br>}</pre><p><strong>HOOK 2</strong>: Meal combo screen</p><pre>&lt;!-- my_meal_graph.xml --&gt;<br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;navigation xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/my_meal_graph&quot;<br>    app:startDestination=&quot;@id/myMealFragment&quot;&gt;</pre><pre>&lt;include app:graph=&quot;@navigation/create_meal_graph&quot; /&gt;</pre><pre>&lt;fragment<br>        android:id=&quot;@+id/myMealFragment&quot;<br>        android:name=&quot;com.example.healthify.MyMealFragment&quot;<br>        android:label=&quot;MyMealFragment&quot;<br>        tools:layout=&quot;@layout/fragment_my_meal&quot;&gt;<br>        &lt;action<br>            android:id=&quot;@+id/action_create_meal&quot;<br>            app:destination=&quot;@id/create_meal_graph&quot; /&gt;<br>    &lt;/fragment&gt;</pre><pre>...<br>&lt;/navigation&gt;</pre><p>Here we have MyMealFragment and we have included create_meal_graph . On click of CREATE A COMBO button user will enter in create meal flow.</p><pre>button.setOnClickListener{<br> Navigation.findNavController(view).navigate(R.id.action_create_meal)<br>}</pre><p><strong>Hook 3</strong>: Search flow, here we will understand nested graph as well as <strong>how to pass data between two destinations</strong></p><p>Navigation allows you to attach data to a navigation operation by defining arguments for a destination. For example, in this case, we can pass meal Type(Breakfast, Lunch, dinner) as an argument in Create meal Fragment.</p><p>In general, you should strongly prefer passing only the minimal amount of data between destinations. For example, you should pass a key to retrieve an object rather than passing the object itself, as the total space for all saved states is limited on Android. If you need to pass large amounts of data, consider using a ViewModel .</p><p>To pass data you need to define an argument in the destination fragment where you want to receive data.</p><p>In this example, we are sending meal type from 3 diff hooks, and it will be received by CreateMealFragment. SO we need to define arg in CreateMealFragment.</p><pre>&lt;fragment<br>        android:id=&quot;@+id/createMealFragment&quot;<br>        android:name=&quot;com.example.healthify.CreateMealFragment&quot;<br>        android:label=&quot;fragment_create_meal&quot;<br>        tools:layout=&quot;@layout/fragment_create_meal&quot; &gt;</pre><pre>&lt;argument<br>         android:name=&quot;mealType&quot;<br>         app:argType=&quot;string&quot;<br>         android:defaultValue=&quot;&quot; /&gt;       <br>    &lt;/fragment&gt;</pre><p>If an argument type supports null values, you can declare a default value of null by using android:defaultValue=&quot;@null&quot;.</p><p>You can check all supported argument types from <a href="https://developer.android.com/guide/navigation/navigation-pass-data">HERE</a>.</p><p>We can pass arguments through “Deeplink” too.</p><pre>&lt;deepLink<br>    android:id=&quot;@+id/deepLink&quot;<br>    app:uri=&quot;www.example.com/createMealFragment/{mealType}&quot;<br>    android:autoVerify=&quot;true&quot;/&gt;</pre><p>From the sender fragment create a bundle of argument and pass it to nav controller.</p><pre>&lt;!-- <strong>search_meal_graph.xml</strong> --&gt;<br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;navigation xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/search_meal_graph&quot;<br>    app:startDestination=&quot;@id/searchMealFragment&quot;&gt;</pre><pre>&lt;include app:graph=&quot;@navigation/create_meal_graph&quot; /&gt;</pre><pre>&lt;fragment<br>        android:id=&quot;@+id/searchMealFragment&quot;<br>        android:name=&quot;com.example.healthify.SearchMealFragment&quot;<br>        android:label=&quot;SearchMealFragment&quot;<br>        tools:layout=&quot;@layout/fragment_search_meal&quot;&gt;<br>        &lt;action<br>            android:id=&quot;@+id/action_add_meal&quot;<br>            app:destination=&quot;@id/create_meal_graph&quot; /&gt;<br>    &lt;/fragment&gt;</pre><pre>...<br>&lt;/navigation&gt;</pre><pre>&lt;!--<strong>searchMealFragment.kt</strong> --&gt;<br>companion object {<br>    const val MEAL_TYPE = &quot;mealType&quot;<br>    // this value should be same as argument name in nav graph<br>}<br>val bundle = <em>bundleOf</em>(MEAL_TYPE <em>to &quot;Breakfast</em>&quot;)</pre><pre><em>findNavController</em>().navigate(R.id.action_add_meal,bundle)</pre><p>This was a small discussion on nested graphs, how to use a nav graph, and how to pass data between two destinations.</p><p>I hope the article was informative for you. If you have any feedback or query please write back to me.</p><p>Till Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db444084ddd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/healthify-tech/navigation-component-designing-navigation-graph-6db444084ddd">Navigation Component, Designing Navigation graph</a> was originally published in <a href="https://medium.com/healthify-tech">HealthifyMe Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HILT — Dependency injection new library]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/healthify-tech/hilt-dependency-injection-new-library-54a1255fa668?source=rss----c612c26b989f---4"><img src="https://cdn-images-1.medium.com/max/2600/1*0KchK-Ft5UAKXRp0ZFpkkQ.jpeg" width="4000"></a></p><p class="medium-feed-snippet">In the previous article, we discussed why dependency injection is important for good app architecture.</p><p class="medium-feed-link"><a href="https://medium.com/healthify-tech/hilt-dependency-injection-new-library-54a1255fa668?source=rss----c612c26b989f---4">Continue reading on HealthifyMe Tech »</a></p></div>]]></description>
            <link>https://medium.com/healthify-tech/hilt-dependency-injection-new-library-54a1255fa668?source=rss----c612c26b989f---4</link>
            <guid isPermaLink="false">https://medium.com/p/54a1255fa668</guid>
            <category><![CDATA[new-in-android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <dc:creator><![CDATA[Karishma Agrawal]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 06:50:11 GMT</pubDate>
            <atom:updated>2020-08-24T06:48:04.195Z</atom:updated>
        </item>
    </channel>
</rss>