<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ronak Sethi on Medium]]></title>
        <description><![CDATA[Stories by Ronak Sethi on Medium]]></description>
        <link>https://medium.com/@ronak.?source=rss-16c56702981d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7UfQD0PtBIUf8GXGt1eEnQ.jpeg</url>
            <title>Stories by Ronak Sethi on Medium</title>
            <link>https://medium.com/@ronak.?source=rss-16c56702981d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:57:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ronak./feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DiffUtil: The RecyclerView’s Personal Trainer for Data Updates!]]></title>
            <link>https://medium.com/@ronak./diffutil-the-recyclerviews-personal-trainer-for-data-updates-bbeec83f6e52?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbeec83f6e52</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[diffutil]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 17:35:46 GMT</pubDate>
            <atom:updated>2024-12-11T17:35:46.174Z</atom:updated>
            <content:encoded><![CDATA[<p>DiffUtil is a utility class in Android that helps efficiently calculate the difference between two lists and output a list of update operations that can be applied to a RecyclerView.Adapter. This allows for smoother updates to RecyclerView items and avoids the need to reload the entire list, which can be computationally expensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ota0vfFGYQnfaAFhqrkvg.png" /></figure><h3>Key Features of DiffUtil:</h3><ol><li><strong>Improved Performance</strong>: Updates only the items that have changed, instead of refreshing the entire list.</li><li><strong>Animation Support</strong>: Automatically animates changes like insertions, deletions, and moves.</li><li><strong>Custom Comparison</strong>: Supports custom logic to define when items are the same or have the same content.</li></ol><h3>How to Use DiffUtil</h3><h4>1. Implement DiffUtil.Callback</h4><p>You need to create a subclass of DiffUtil.Callback and override its methods:</p><pre>class MyDiffUtilCallback(<br>    private val oldList: List&lt;MyData&gt;,<br>    private val newList: List&lt;MyData&gt;<br>) : DiffUtil.Callback() {</pre><pre>    override fun getOldListSize(): Int = oldList.size</pre><pre>    override fun getNewListSize(): Int = newList.size</pre><pre>    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        // Compare unique identifiers for items<br>        return oldList[oldItemPosition].id == newList[newItemPosition].id<br>    }</pre><pre>    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        // Compare the contents of the items<br>        return oldList[oldItemPosition] == newList[newItemPosition]<br>    }<br>}</pre><h4>2. Apply DiffUtil.DiffResult</h4><p>Generate the DiffResult and apply it to the adapter:</p><pre>val diffCallback = MyDiffUtilCallback(oldList, newList)<br>val diffResult = DiffUtil.calculateDiff(diffCallback)</pre><pre>// Update the old list and notify the adapter<br>oldList.clear()<br>oldList.addAll(newList)<br>diffResult.dispatchUpdatesTo(adapter)</pre><h4>3. Using AsyncListDiffer (Recommended for Efficiency)</h4><p>For larger lists, you can use AsyncListDiffer, which handles background thread execution automatically:</p><pre>class MyAdapter : RecyclerView.Adapter&lt;MyViewHolder&gt;() {<br>    private val differ = AsyncListDiffer(this, MyDiffUtilCallback())</pre><pre>    var items: List&lt;MyData&gt;<br>        get() = differ.currentList<br>        set(value) = differ.submitList(value)</pre><pre>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {<br>        // Inflate layout and return ViewHolder<br>    }</pre><pre>    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {<br>        holder.bind(items[position])<br>    }</pre><pre>    override fun getItemCount(): Int = items.size<br>}</pre><h3>When to Use DiffUtil</h3><p><strong>Use Cases:</strong></p><ul><li>Use DiffUtil whenever your RecyclerView updates involve dynamic data changes, such as adding, removing, or modifying list items.</li><li>It’s particularly useful for large datasets, where updating the entire list is inefficient.</li><li>Applications that need smooth animations for item changes.</li><li>Scenarios where performance is a priority and resources are constrained.</li></ul><p><strong>Avoid:</strong></p><ul><li>Small, static lists that don’t change often.</li><li>Scenarios requiring constant real-time updates, like live sports scores or stock tickers.</li></ul><h3><strong>Pros and Cons of Using </strong><strong>DiffUtil</strong></h3><h3>Pros</h3><p><strong>Efficient Performance</strong>:<br>Only updates the parts of the RecyclerView that have changed, reducing the overhead of reloading the entire list.</p><p><strong>Built-in Animations</strong>:<br>Automatically provides smooth animations for changes like additions, deletions, and moves without extra code.</p><p><strong>Customisable</strong>:<br>Allows developers to define their own logic for identifying when items are the same (areItemsTheSame()) or when contents have changed (areContentsTheSame()).</p><p><strong>Ease of Use</strong>:<br>Works seamlessly with RecyclerView.Adapter and integrates well with other Android UI components.</p><p><strong>Supports Large Datasets</strong>:<br>Ideal for applications with large lists where full updates can be costly in terms of memory and processing power.</p><p><strong>Thread-Safe Options</strong>:<br>Tools like AsyncListDiffer enable background computation of differences, improving UI responsiveness.</p><h3>Cons</h3><p><strong>Initial Complexity</strong>:<br>Setting up DiffUtil.Callback and understanding its lifecycle can be challenging for beginners.</p><p><strong>No Built-in Diff Logic</strong>:<br>Requires developers to implement the logic for identifying item uniqueness and content changes.</p><p><strong>Not Suitable for Frequent Updates</strong>:<br>In cases of very rapid data changes, the computation of differences may introduce slight delays.</p><p><strong>Overhead for Small Lists</strong>:<br>For very small datasets, the overhead of calculating differences might not justify its use compared to simply reloading the list.</p><p><strong>Verbose Code</strong>:<br>Implementing the required methods and handling edge cases can result in additional boilerplate code.</p><p><strong>DiffUtil is an essential tool for efficiently updating </strong><strong>RecyclerView in Android, offering smooth animations and optimised performance. While it requires initial setup, its benefits for managing dynamic data make it a must-have for modern app development.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbeec83f6e52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MotionLayout — Any View can Dance!]]></title>
            <link>https://medium.com/@ronak./motionlayout-any-view-can-dance-1e08035e96b7?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e08035e96b7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 20:02:45 GMT</pubDate>
            <atom:updated>2020-06-10T18:09:59.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>MotionLayout — Any View can Dance!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*n0PtG8B1Fssww-7eSixXbw.png" /></figure><h3>Introduction to MotionLayout</h3><p>MotionLayout is a subclass of Android ConstraintLayout which allows you to animate just about any view or layout in the app very easily. The good news is that it is backward-compatible to API level 14 (Android 4.0), so the animations you create can pretty much work on all Android versions your users might use. Even though you can create the MotionLayout animations with Android Studio &lt; 4.0, there are better tools in AS 4.0 that I’d strongly recommend to use when you work with MotionLayout.</p><h3>Project Setup</h3><p>To get things started, here’s what you do:</p><ol><li>Open a new project.</li><li>Select an <em>Empty Activity</em> Project Template.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hgcKCyzqdo24HlkF.png" /></figure><p>3. Type any name for the project and select Kotlin from the language</p><p>4. Click Finish.</p><p>5. Run the project to see the look of your initial app i.e. an app with a single activity with “Hello World!” text in the center.</p><h3>Adding Dependency</h3><p>Since MotionLayout is a part of ConstraintLayout and currently only works in v2.0, in order to use it, we first need to update or add our ConstraintLayout dependency:</p><ol><li>Open <em>build.gradle </em>(Module)</li><li>Add this line in the dependency section or replace your <em>constraintlayout</em> dependency with:</li></ol><pre>   implementation &#39;androidx.constraintlayout:constraintlayout:2.0.0-beta6&#39;</pre><p>3. Sync the project.</p><h3><strong>Updates to the Code</strong></h3><p>Now to get rid of the toolbar, navigation bar, and status bar, and add color to the background, do the following:</p><ol><li>Open styles.xml</li><li>Replace the base theme’s parent from:</li></ol><pre>Theme.AppCompat.Light.DarkActionBar <br>to <br><em>Theme.AppCompat.Light.NoActionBar. </em></pre><p>(If you run the app at this point, you’ll see that the action bar/toolbar is gone)</p><ol><li>Add new customizations for your app by setting <em>android:windowFullscreen </em>to true (which hides the status bar) and setting <em>android:background </em>to our primary color (which adds a background color to our activity)</li><li>Run the App.</li></ol><p>You now basically see an empty screen with our colorPrimary as the background i.e. black.</p><h3>Adding Assets</h3><p>I imported an image directly to the drawable folder, you can even add vector drawables.</p><h3>Adding Motion</h3><p>To bring the app UI a life, there are a few easy steps that you need to do (these steps are of Android Studio 4.0, so don’t get confused):</p><ol><li>Open <em>activity_main.xml.</em></li><li>In the Design tab, under Component Tree, right-click and select <em>Convert to MotionLayout.</em></li></ol><p>This should automatically change our parent layout from ConstraintLayout to MotionLayout, show a slightly different Design view, and also add a new <em>activity_motion_scene.xml</em> under the XML directory.</p><p>In order to create the timeline, do the following:</p><ol><li>While the <em>activity_main.xml</em> is opened under the Design view, click the arrow between start and end ConstraintSets to open the Transition timeline for ImageView.</li><li>Click the Create Keyframes icon at the top right of the Transition timeline and click KeyAttribute.</li><li>Select imageView from ID, Set its Position and Attribute to scaleX.</li><li>Repeat the same for scaleY.</li><li>Add two other KeyAttributes for scaleX and scaleY with Position 20.</li></ol><p>6. Click on each diamonds for scaleX and scaleY at Position 20 and in the Attributes section, change the scaleX and scaleY to 0.5 (this achieves the scaled-down motion from position 0 to 20).</p><p>7. Add two new KeyAttributes for both the scales at Position 40 and keep their scales to 0.7 (this achieves the rest period of the logo from position 20 to 40 before the huge scaled up motion).</p><p>8. Add two new KeyAttributes for both the scales at Position 100 and set their scales to 4.0 (this achieves the final scaled up effect that fills the whole screen)</p><p>Same for the TextView I added in my MotionLayout.</p><p>Here is the code to my activity_main_scene:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560de9d05abfd53bc6e033dc0c7a437b/href">https://medium.com/media/560de9d05abfd53bc6e033dc0c7a437b/href</a></iframe><p>In order to see if we’ve done the animation right, we’re going to trigger it with a click on the screen, and for that:</p><ol><li>Select the Click Handler</li><li>In the popup that opens, select View you want from where the animation gets triggered. I selected BaseLayout to handle click.</li></ol><p>Run the app, and here’s your newly constructed animation using MotionLayout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*27U0WvRVKsIxzV9cJNx-7w.gif" /></figure><p>Open the <em>activity_main_scene.xml </em>to look at the file from where you can make further tweaks to the animation for further perfection.</p><p>Clap on it, if you like it!</p><p><strong>Also, Let’s connect on</strong> <a href="https://twitter.com/rounakk987"><strong>Twitter</strong></a><strong>,</strong> <a href="https://www.linkedin.com/in/ronak-sethi-2610/"><strong>Linkedin</strong></a><strong>, and </strong><a href="https://github.com/ronu2610"><strong>Github</strong></a><strong>.</strong></p><p><a href="https://developer.android.com/training/constraint-layout/motionlayout">Manage motion and widget animation with MotionLayout</a></p><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e08035e96b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Coroutine — Android]]></title>
            <link>https://medium.com/@ronak./exploring-coroutine-android-76eda9db9f15?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/76eda9db9f15</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Mon, 11 May 2020 02:57:45 GMT</pubDate>
            <atom:updated>2020-05-11T03:41:09.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Coroutine — Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KvnLSMzRvhpKJec6" /></figure><p>A <em>coroutine</em> is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. <a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html">Coroutines</a> were added to Kotlin in version 1.3 and are based on established concepts from other languages.</p><p>On Android, coroutines help to solve two primary problems:</p><ul><li>Manage long-running tasks that might otherwise block the main thread and cause your app to freeze.</li><li>Providing <em>main-safety</em>, or safely calling network or disk operations from the main thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*c_jZbAcEN9CIJ0cN" /></figure><p>The most interesting thing is that a thread can stop executing a coroutine at some specific “suspension points”, and go do some other work. It can resume executing the coroutine later on, or another thread could even take over.</p><p>When we use GlobalScope.launch, we create a top-level coroutine. Even though it is light-weight, it still consumes some memory resources while it runs. If we forget to keep a reference to the newly launched coroutine it still runs.</p><h3>Suspending functions</h3><p>You may find functions like kotlinx’s delay or Ktor’s HttpClient.post that need to wait for something or do intensive work before returning, and are marked with the suspend keyword.</p><pre><strong>suspend</strong> <strong>fun </strong>delay(timeMillis: Long) {...}<br><strong>suspend fun</strong> someNetworkCallReturningValue(): SomeType {<br> ...<br>}</pre><p>These are called <strong><em>suspending functions</em></strong>. As we’ve just seen:</p><blockquote><em>Suspending functions may suspend the execution of the current coroutine without blocking the current thread.</em></blockquote><h3>Using coroutines for long-running tasks</h3><p>Coroutines are a way to simplify the code used to manage long-running tasks like fetchDocs. To explore how coroutines make the code for long-running tasks simpler, let’s rewrite the callback example above to use coroutines.</p><pre>// Dispatchers.Main<br>suspend fun fetchData() {<br>    // Dispatchers.Main<br>    val result = get(url-here)<br>    // Dispatchers.Main<br>    show(result)<br>}<br>suspend fun get(url: String) = withContext(Dispatchers.IO){/*...*/} <br>//Dispatcher.IO -main safety block</pre><p>Doesn’t this code block the main thread? How does it return a result from get without waiting for the network request and blocking? It turns out coroutines provide a way for Kotlin to execute this code and never block the main thread.</p><p>Coroutines build upon regular functions by adding two new operations. In addition to <strong>invoke</strong> (or call) and <strong>return</strong>, coroutines add <strong>suspend</strong> and <strong>resume</strong>.</p><ul><li><strong>suspend</strong> — pause the execution of the current coroutine, saving all local variables</li><li><strong>resume</strong> — continue a suspended coroutine from the place it was paused</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*Ni4kYit_Dd1c4KHt" /></figure><p>This functionality is added by Kotlin by the suspend keyword on the function. You can only call suspend functions from other suspend functions, or by using a coroutine builder like <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html">launch</a> to start a new coroutine.</p><blockquote><em>Suspend and resume work together to replace callbacks.</em></blockquote><h3>Dispatchers</h3><ol><li><strong>Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html"><strong>Main</strong></a><br>Main thread on Android, interact with the UI, and perform light work.<br> — Calling suspend functions <br> — Call UI functions <br> — Updating LiveData</li><li><strong>Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html"><strong>IO</strong></a><br>Optimized for disk and network IO off the main thread.<br> — Database*<br> — Reading/writing files<br> — Networking**</li><li><strong>Dispatchers.</strong><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-default.html"><strong>Default</strong></a><strong> </strong><br>Optimized for CPU intensive work off the main thread.<br> — Sorting a list <br> — Parsing JSON<br> — DiffUtils</li></ol><h3>Coroutine with Retrofit</h3><p>Coroutines give us all the benefit of asynchronous and non-blocking behavior but without the lack of readability. We’ll see how we can use coroutines to perform network requests without blocking the underlying thread and without using callbacks. For network requests, we’ll use the <a href="https://square.github.io/retrofit/">Retrofit</a> library which already supports coroutines.</p><p>Here, I have done an example to fetch a list of news sources:</p><blockquote>Firstly add the dependency for coroutine:</blockquote><pre>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.72&quot;</pre><blockquote>Source Item class</blockquote><pre>class Source {<br>    var key: String? = null<br>    var name: String? = null<br>    var lang: String? = null<br>    var img: String? = null<br>}</pre><blockquote>Interface for network request</blockquote><pre>interface MyApi {<br>    @GET(&quot;/news_source&quot;)<br>    suspend fun getAllSources(<br>        @Query(&quot;api_key&quot;) api_key: String?<br>    ): Response&lt;List&lt;SourceBean&gt;&gt;<br>}</pre><blockquote>Here we create retrofit to use it with coroutine in the <em>GlobalScope</em> to fetch data.</blockquote><pre>val retrofit = Retrofit.Builder()<br>        .baseUrl(BASE_URL)<br>        .addConverterFactory(GsonConverterFactory.create())<br>        .build()<br>        .create(MyApi::class.<em>java</em>)<br><br>GlobalScope.<em>launch</em>(Dispatchers.Main) <strong>{<br></strong>    val comments = withContext(Dispatchers.IO) <strong>{ </strong>retrofit.getAllSources(API_KEY) <strong>}<br></strong>    comments.body()?.<em>let </em><strong>{ </strong>setUpRecyclerView(<strong>it</strong>) <strong>}<br>}</strong></pre><p>Now u can see in the last code that I used a function of <em>setUpRecyclerView() </em>which basically is to display the data fetched to the screen using recycler view.</p><p>That’s it from my side.<br>Thank you for reading!</p><p>To know more about coroutine just go through these links:</p><ul><li><a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html">Coroutines Guide - Kotlin Programming Language</a></li><li><a href="https://github.com/kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md">Kotlin/kotlinx.coroutines</a></li></ul><blockquote>Clap for it, if you like it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76eda9db9f15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxAndroid]]></title>
            <link>https://medium.com/@ronak./rxandroid-d85f19e8449d?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d85f19e8449d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxandroid]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Mon, 04 May 2020 01:58:45 GMT</pubDate>
            <atom:updated>2020-05-04T01:58:45.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1sK-uaiI6NxBHmrx.jpg" /></figure><p>RxAndroid is an extension to RxJava. It providers a scheduler to run code in the main thread of Android. It also provides the ability to create a scheduler that runs on an Android handler class. With this schedulers, you can define an observable which does its work in a background thread, and post our results to the main thread. This allows for example to replace a AsyncTask implementations that RxJava.</p><blockquote><em>The Observer pattern done right. ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.</em></blockquote><p>To use RxJava in Android add the following dependency to your build.gradle file.</p><pre>compile <strong>&#39;io.reactivex.rxjava2:rxandroid:2.0.1&#39;</strong><br>compile <strong>&#39;io.reactivex.rxjava2:rxjava:2.0.8&#39;</strong></pre><p>For example, you can define a long-running operation via the following observable.</p><pre><strong>final</strong> Observable<strong>&lt;</strong>Integer<strong>&gt;</strong> serverDownloadObservable <strong>=</strong> Observable<strong>.</strong>create<strong>(</strong>emitter <strong>-&gt;</strong> <strong>{</strong><br>        SystemClock<strong>.</strong>sleep<strong>(1000);</strong> <em>// simulate delay</em><br>        emitter<strong>.</strong>onNext<strong>(5);</strong><br>        emitter<strong>.</strong>onComplete<strong>();</strong><br>    <strong>});</strong></pre><p>You can now subscribe to this observable. This triggers its execution and provides the subscribe with the required information.</p><pre>subscribeOn(Schedulers.io())</pre><p>Threading in Rxandroid is done with the help of schedulers. To be more precise schedulers are like a ThreadPool managing one or more Threads. So, If a schedulers need to perform a task then it will take a Thread from pool and will run that task on it.</p><p>Subscribeon() specifies on which Scheduler the work will be done.In our case it is to make a network and <strong>Schedulers.io()</strong> is backed by unbounded ThreadPool. It can be used for non CPU-intensive I/O type like network calls and database calls etc.And if you want you can dig more about it and you really should.</p><p>For example, let&#39;s assume you assign this to a button.</p><pre>serverDownloadObservable<strong>.</strong>                        observeOn<strong>(</strong>AndroidSchedulers<strong>.</strong>mainThread<strong>()).</strong><br>                        subscribeOn<strong>(</strong>Schedulers<strong>.</strong>io<strong>()).</strong>  <br>                        subscribe<strong>(</strong>integer <strong>-&gt;</strong> <strong>{</strong><br>                            updateTheUserInterface<strong>(</strong>integer<strong>);</strong> <em>// this methods updates the ui</em><br>                            view<strong>.</strong>setEnabled<strong>(true);</strong> <em>// enables it again</em><br>                        <strong>});</strong><br>            <strong>}</strong><br><strong>.</strong>subscribeOn<strong>(</strong>Schedulers<strong>.</strong>io<strong>())</strong><br><strong>.</strong>observeOn<strong>(</strong>AndroidSchedulers<strong>.</strong>mainThread<strong>());</strong></pre><p>The subscriber observes in the main thread while Observable is called outside the main thread.</p><p>As we are only interested in the final result, we could also use a Single.</p><pre>Subscription subscription <strong>=</strong> Single<strong>.</strong>create<strong>(new</strong> Single<strong>.</strong>OnSubscribe<strong>()</strong> <strong>{</strong><br>           <strong>@Override</strong><br>           <strong>public</strong> <strong>void</strong> call<strong>(</strong>SingleSubscriber singleSubscriber<strong>)</strong> <strong>{</strong><br>               String result <strong>=</strong> doSomeLongRunningStuff<strong>();</strong><br>               singleSubscriber<strong>.</strong>onSuccess<strong>(</strong>value<strong>);</strong><br>           <strong>}</strong><br>       <strong>})</strong><br>       <strong>.</strong>subscribeOn<strong>(</strong>Schedulers<strong>.</strong>io<strong>())</strong><br>       <strong>.</strong>observeOn<strong>(</strong>AndroidSchedulers<strong>.</strong>mainThread<strong>())</strong><br>       <strong>.</strong>subscribe<strong>(new</strong> Action1<strong>()</strong> <strong>{</strong><br>           <strong>@Override</strong><br>           <strong>public</strong> <strong>void</strong> call<strong>(</strong>String value<strong>)</strong> <strong>{</strong><br>               <em>// onSuccess</em><br>               updateTheUserInterface<strong>();</strong> <em>// this methods updates the ui</em><br>           <strong>}</strong><br>       <strong>},</strong> <strong>new</strong> Action1<strong>()</strong> <strong>{</strong><br>           <strong>@Override</strong><br>           <strong>public</strong> <strong>void</strong> call<strong>(</strong>Throwable throwable<strong>)</strong> <strong>{</strong><br>               <em>// handle onError</em><br>           <strong>}</strong><br>       <strong>});</strong></pre><h3>Unsubscribe to avoid memory leaks</h3><p>Observable.subscribe() returns a Subscription (if you are using a Flowable) or a Disposable object. To prevent a possible (temporary) memory leak, unsubscribe from your observables in the ‘onStop()’ method of the activity or fragment. For example, for a Disposable object you could do the following:</p><pre><strong>@Override</strong><br>    <strong>protected</strong> <strong>void</strong> onDestroy<strong>()</strong> <strong>{</strong><br>        <strong>super.</strong>onDestroy<strong>();</strong><br>        <strong>if</strong> <strong>(</strong>bookSubscription <strong>!=</strong> <strong>null</strong> <strong>&amp;&amp; </strong> <strong>!</strong>bookSubscription<strong>.</strong>isDisposed<strong>())</strong> <strong>{</strong><br>            bookSubscription<strong>.</strong>dispose<strong>();</strong><br>        <strong>}</strong><br>    <strong>}</strong></pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d85f19e8449d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger 2 —Dependency Injection — Why to use and its Dependency Provider]]></title>
            <link>https://medium.com/@ronak./dagger-2-dependency-injection-why-to-use-and-its-dependency-provider-f3fafd383d61?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3fafd383d61</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger-android]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 11:21:46 GMT</pubDate>
            <atom:updated>2020-04-25T11:21:46.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dagger 2 —Dependency Injection — Why to use and its Dependency Provider</h3><p>Hey Folks! new to Dagger 2? So Dagger 2 is a Dependency Injection Framework that uses code generation and is based on annotations. The generated code is very relatively easy to read and debug. For more about Dependency Injection, check-out my last <a href="https://link.medium.com/te21PmvDP5">blog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*P2ytd6QSeyQprWHn.png" /></figure><blockquote>Why to use Dagger2?</blockquote><ol><li>Small size of the Library.</li><li>Simple unit and integration testing.</li><li>Easy configuration of complex dependencies.</li><li>Simplifies access to shared instances.</li></ol><p>Managing the dependencies of different classes by yourself, without relying on a library. This is called dependency injection by hand, or manual dependency injection. But when your app grows and becomes more complex, manual dependency injection can be very tedious.</p><blockquote>Manual dependency injection presents several problems:</blockquote><ol><li>Boilerplate Code</li><li>Not Flexible</li></ol><p>DI-based approach benefits in Reusability and testing of code. Dagger comprise to be the most popular framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*l-atycbg2XZtJhr_.png" /></figure><p>There are many annotations that are used Dagger 2 but the most common ones are:</p><ul><li>@Module and @Provides: define classes and methods which provide dependencies.</li><li>@Inject: request dependencies. Can be used on a constructor, a field, or a method.</li><li>@Component: enable selected modules and used for performing dependency injection</li></ul><p>Dagger 2 uses generated code to access the fields and not reflection. Therefore it is not allowed to use private fields for field injection.</p><h3>Dependency providers</h3><p>The term <em>dependency injection context</em> is typically used to describe the set of objects which can be injected.</p><ul><li>In Dagger 2, <em>classes</em> annotated with @Module are responsible for providing objects which can be injected.</li><li>Such classes can define methods annotated with @Provides. The returned objects from these methods are available for dependency injection.</li><li>Methods annotated with @Provides can also express dependencies via method parameters. These dependencies are fulfilled by Dagger 2, if possible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*btu2bg59h5WWje2z.png" /></figure><p>Let’s take an example where we take two objects:</p><ol><li>Main object. (Main is a class)</li><li>Log object. (Log is an interface)</li></ol><p>The key difference between providing a Main object and a Log object is that Log is an interface, and many different implementations may be available for this interface, and Dagger 2 doesn’t know how to provide the desired implementation for this interface.</p><p>This is where @Module and @Provides come into play.</p><p>So we add some more complexity to our component.</p><pre><strong>@Component</strong>(modules = {<strong>LogModule</strong>.class})<br><strong>@Singleton</strong><br><strong>interface</strong> <strong>LogComponent</strong> {<br>    <strong>Main</strong> <strong>providesMain</strong>();<br>}<br><strong>@Module</strong><br><strong>class</strong> <strong>LogModule</strong> {<br>    <strong>@Provides</strong><br>    <strong>@Singleton</strong><br>    <strong>Log</strong> <strong>providesLogger</strong>(<strong>ConsoleLogger</strong> logger) {<br>        <strong>return</strong> logger;<br>    }<br>}</pre><p>Note that the providesLogger() method is declared, but an object is <strong>NOT</strong> created here! We could simply do the following in this method and it would work.</p><pre><strong>Log</strong> <strong>providesLogger</strong>() {<br>    <strong>return</strong> <strong>new</strong> <strong>ConsoleLogger</strong>();<br>}</pre><p>However, by adding a parameter to this providesLog() method, we are telling Dagger 2 to figure out how to get an <strong>instance</strong> of ConsoleLogger on its own, but then return it <strong>as</strong> a Log interface. That’s pretty slick!</p><p>In order to make this happen, we have to make the ConsoleLogger class more complex though.</p><pre><strong>@Singleton</strong><br><strong>class</strong> <strong>ConsoleLogger</strong> <strong>implements</strong> <strong>Log</strong> {</pre><pre>    <strong>@Inject</strong><br>    <strong>ConsoleLogger</strong>(){}</pre><pre>    <strong>@Override</strong><br>    <strong>public</strong> <strong>void</strong> <strong>log</strong>(<strong>String</strong> msg) {<br>        <strong>System</strong>.out.println(msg);<br>    }<br>}</pre><p>By simply adding a no-arg constructor and marking it w/ @Inject we are able to tell Dagger 2 how to provide an instance of ConsoleLogger that it can provide! How awesome is that!</p><p>Also, note that the @Singleton annotation is applied to the class and not the method since we are using a @Inject. If we were using a provider and module then the @Singleton annotation would not be at the class level; this is only for @Inject.</p><p>Finally, we have to change the Main class so that it knows how to work w/ the LogModule that we just added.</p><pre><strong>class</strong> <strong>Main</strong> {<br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>main</strong>(<strong>String</strong>[] args) {<br>        <strong>DaggerLogComponent</strong>.builder().build().providesMain().run();<br>    }<br>    <strong>@Inject</strong><br>    <strong>Main</strong>() {}</pre><pre>    <strong>@Inject</strong><br>    <strong>Log</strong> logger;</pre><pre>    <strong>public</strong> <strong>void</strong> <strong>run</strong>() {<br>        logger.log(&quot;Hello world!!! Simple Dagger&quot;);<br>    }<br>}</pre><h3>@Bind shortcut</h3><p>Instead of this:</p><pre><strong>@Provides</strong> <strong>@Singleton</strong> <br><strong>Log</strong> <strong>providesLogger</strong>(<strong>ConsoleLogger</strong> logger) { <strong>return</strong> logger; }</pre><p>We could write:</p><pre><strong>@Binds</strong> <strong>@Singleton</strong> <br><strong>abstract</strong> <strong>Log</strong> <strong>providesLogger</strong>(<strong>ConsoleLogger</strong> logger);</pre><p>It is possible to have arguments in the constructor that are annotated with @Inject as long as the parameters in the constructor are objects that Dagger 2 knows how to create. In order to use this:</p><ol><li>Simply make the Module class abstract</li><li>Make the non-@Binds methods, ie the @Provides methods static.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*EgKsTlfsuUDy7SKDtFVXYw.png" /></figure><blockquote>That’s it from my side.</blockquote><blockquote>Thanks for reading.</blockquote><blockquote>Clap on it, if you like it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fafd383d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection — Android]]></title>
            <link>https://medium.com/@ronak./dependency-injection-android-e86e50fa996e?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86e50fa996e</guid>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 19:18:03 GMT</pubDate>
            <atom:updated>2020-04-19T23:20:06.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dependency Injection — Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PnL9fVjkz_kSLh9p2nh18A.png" /></figure><p>Before understanding what it means in programming, lets first see what it means in general as it will help us understand the concept better.</p><p>Dependency or dependent means relying on something for support. like if I say we are relying too much on digital mediums that it means we are dependent on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*t9p2q5FiMSdyYFbo" /></figure><p>In programming, classes require references to other classes. For example, a Bike class might need a reference to an Engine class.</p><p>These required classes are called dependencies and in this example, the Bike class is dependent on having an instance of the Engine class to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*PUpaXUUYpYEo0ZK2uP1ksg.png" /></figure><p>Here’s an example, without dependency injection, representing a Bike that creates its own Engine dependency in code looks like this:</p><pre>class Bike {<br>    private Engine engine = new Engine();<br>    public void start() {<br>        engine.start();<br>    }<br>}</pre><pre>class MyApp {<br>    public static void main(String[] args) {<br>        Bike bike = new Bike();<br>        bike.start();<br>    }<br>}</pre><p>That was not an example of dependency injection because the Bike class is constructing its own Engine. This can be problematic because:</p><ul><li>Bike and Engine are tightly coupled.</li><li>The hard dependency on Engine makes testing more difficult.</li></ul><p>What does the code look like with dependency injection? Instead of each instance of Bike constructing its own engine object on initialization, it receives an Engine object as a parameter in its constructor:</p><pre>class Bike {<br>    private final Engine engine;<br>    public Bike(Engine engine) {<br>        this.engine = engine;<br>    }<br>    public void start() {<br>        engine.start();<br>    }<br>}</pre><pre>class MyApp {<br>    public static void main(String[] args) {<br>        Engine engine = new Engine();<br>        Bike bike = new Bike(engine);<br>        bike.start();<br>    }<br>}</pre><p>The main function uses Bike. Because Bike depends on Engine, the app creates an instance of Engine and then uses it to construct an instance of Bike.</p><blockquote>The benefits of this, DI-based approach are:</blockquote><ul><li>Reusability of Bike. You can pass in different implementations of Engine to Bike.</li><li>Easy testing ofBike.</li></ul><p>Managing the dependencies of the different classes by yourself, without relying on a library. This is called dependency injection by hand, or manual dependency injection like what we did in the above Bike example. But when your app grows and becomes more complex, manual dependency injection can be very tedious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*v4rAYf57dAxUW-B6FKEpCA.png" /></figure><p>Manual dependency injection presents several problems:</p><ol><li>Boilerplate Code</li><li>Not Flexible</li></ol><h3>Got tensed? Now what TODO?</h3><blockquote>Ans: Use Dagger.</blockquote><p>Dagger is a fully static, compile-time dependency injection framework for Java, Kotlin and Android. Dagger2 is a dependency injection framework, uses code generation and is based on annotations. The generated code is very relatively easy to read and debug.</p><blockquote>Why Dagger?</blockquote><ol><li>Small size of the Library.</li><li>Simple unit and integration testing.</li><li>Easy configuration of complex dependencies.</li><li>Simplifies access to shared instances.</li></ol><p>That’s it from my side.</p><p>Thanks for reading.</p><p>Clap on it, if you like it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86e50fa996e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Views — Android]]></title>
            <link>https://medium.com/@ronak./custom-views-android-4abd8f63918d?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4abd8f63918d</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[custom-view-android]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[xml]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 07:19:37 GMT</pubDate>
            <atom:updated>2020-04-19T23:20:50.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Views — Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*bYwiPgOTIOSKqQxi.png" /><figcaption>Basic Widgets Hierarchy</figcaption></figure><p>Android consists of different View classes that are used in building a typical app. But if you want UI customization, Different user interaction, Displaying different types of data, Reusability and Some performance optimization, you may need to extend a widget.</p><p>Two Ways to create <strong><em>custom views</em></strong> in Android:</p><ol><li>Extending the <strong><em>View class — </em></strong>Building the view from scratch</li><li>Extending <strong><em>already existing views — </em></strong>Building the view from available views (TextView, ImageView, etc).</li></ol><ul><li>Firstly create a custom view class by any of the above ways. Using the first way to create a fully customized new component as a new super component while using the second way is to create a component having attributes of the view extended to that custom view.</li></ul><p>Way 1: The class is defined with the following line:<br>public class MyView extends View{</p><p>Way 2: The class is defined with the following line:<br>public static class LinedEditText extends EditText{</p><blockquote>On building the view from scratch, you have to create your own event listeners, property accessors and modifiers, and possibly more sophisticated behavior in your component class as well.</blockquote><ul><li>After creating custom view class define and specify some custom attributes, add the View to our layout XML.</li></ul><blockquote>Define custom attributes for your view in a <em>&lt;declare-styleable&gt; </em>resource element</blockquote><pre>&lt;resources&gt;<br>   &lt;declare-styleable name=&quot;MyView&quot;&gt;<br>       &lt;attr name=&quot;showText&quot; format=&quot;boolean&quot; /&gt;<br>       &lt;attr name=&quot;labelPosition&quot; format=&quot;enum&quot;&gt;<br>           &lt;enum name=&quot;left&quot; value=&quot;0&quot;/&gt;<br>           &lt;enum name=&quot;right&quot; value=&quot;1&quot;/&gt;<br>       &lt;/attr&gt;<br>   &lt;/declare-styleable&gt;<br>&lt;/resources&gt;</pre><p>That’s how your MyView class reads its attributes:</p><pre>public MyView(Context context, AttributeSet attrs) {<br>   super(context, attrs);<br>   TypedArray a = context.getTheme().obtainStyledAttributes(<br>        attrs,<br>        R.styleable.MyView,<br>        0, 0);</pre><pre>   try {<br>       mShowText = a.getBoolean(R.styleable.MyView_showText, false);<br>       textPos = a.getInteger(R.styleable.MyView_labelPosition, 0);<br>   } finally {<br>       a.recycle();<br>   }<br>}</pre><ul><li>Now, Override some methods of Superclass. The superclass methods to override start with ‘on&#39;, for example, <a href="https://developer.android.com/reference/android/view/View#onDraw(android.graphics.Canvas)">onDraw()</a>, <a href="https://developer.android.com/reference/android/view/View#onMeasure(int,%20int)">onMeasure()</a>, and <a href="https://developer.android.com/reference/android/view/View#onKeyDown(int,%20android.view.KeyEvent)">onKeyDown()</a>.</li><li>Now use your new class created in place of the view to use it in the activity.</li></ul><blockquote><strong><em>Some of the standard methods that the framework calls: </em></strong><a href="https://developer.android.com/guide/topics/ui/custom-components#extend-ondraw-and-onmeasure"><em>Source</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*qDFPZ2a_MfYcAkPt.png" /></figure><blockquote><strong>Creation</strong></blockquote><p><strong>Constructors </strong>— There is a form of the constructor that is called when the view is created from code and a form that is called when the view is inflated from a layout file.</p><p><a href="https://developer.android.com/reference/android/view/View#onFinishInflate()"><strong>onFinishInflate()</strong></a><strong> — </strong>Called after a view and all of its children have been inflated from XML.</p><blockquote><strong>Layout</strong></blockquote><p><a href="https://developer.android.com/reference/android/view/View#onMeasure(int,%20int)"><strong>onMeasure( int)</strong></a><strong> — </strong>Called to determine the size requirements for this view and all of its children.</p><p><a href="https://developer.android.com/reference/android/view/View#onLayout(boolean,%20int,%20int,%20int,%20int)"><strong>onLayout( int, int, int, int)</strong></a><strong> — </strong>Called when this view should assign a size and position to all of its children.</p><p><a href="https://developer.android.com/reference/android/view/View#onSizeChanged(int,%20int,%20int,%20int)"><strong>onSizeChanged( int, int, int)</strong></a><strong> — </strong>Called when the size of this view has changed.</p><blockquote><strong>Drawing</strong></blockquote><p><a href="https://developer.android.com/reference/android/view/View#onDraw(android.graphics.Canvas)"><strong>onDraw(</strong></a><strong> — </strong>Called when the view should render its content.</p><blockquote><strong>Event processing</strong></blockquote><p><a href="https://developer.android.com/reference/android/view/View#onKeyDown(int,%20android.view.KeyEvent)"><strong>onKeyDown( KeyEvent)</strong></a><strong> — </strong>Called when a new key event occurs.</p><p><a href="https://developer.android.com/reference/android/view/View#onKeyUp(int,%20android.view.KeyEvent)"><strong>onKeyUp( KeyEvent)</strong></a><strong> — </strong>Called when a key up event occurs.</p><p><a href="https://developer.android.com/reference/android/view/View#onTrackballEvent(android.view.MotionEvent)"><strong>onTrackballEvent(</strong></a><strong> — </strong>Called when a trackball motion event occurs.</p><p><a href="https://developer.android.com/reference/android/view/View#onTouchEvent(android.view.MotionEvent)"><strong>onTouchEvent(</strong></a><strong> — </strong>Called when a touch screen motion event occurs.</p><blockquote><strong>Focus</strong></blockquote><p><a href="https://developer.android.com/reference/android/view/View#onFocusChanged(boolean,%20int,%20android.graphics.Rect)"><strong>onFocusChanged( int, Rect)</strong></a><strong> — </strong>Called when the view gains or loses focus.</p><p><a href="https://developer.android.com/reference/android/view/View#onWindowFocusChanged(boolean)"><strong>onWindowFocusChanged(</strong></a><strong> — </strong>Called when the window containing the view gains or loses focus.</p><blockquote><strong>Attaching</strong></blockquote><p><a href="https://developer.android.com/reference/android/view/View#onAttachedToWindow()"><strong>onAttachedToWindow()</strong></a><strong> — </strong>Called when the view is attached to a window.</p><p><a href="https://developer.android.com/reference/android/view/View#onDetachedFromWindow()"><strong>onDetachedFromWindow()</strong></a><strong> — </strong>Called when the view is detached from its window.</p><p><a href="https://developer.android.com/reference/android/view/View#onWindowVisibilityChanged(int)"><strong>onWindowVisibilityChanged(</strong></a><strong> — </strong>Called when the visibility of the window containing the view has changed.</p><blockquote><strong>Update</strong></blockquote><p><strong>invalidate()— </strong>Called to simply redraw view using <a href="https://developer.android.com/reference/android/view/View#onDraw(android.graphics.Canvas)"><strong>onDraw(</strong></a><strong>)</strong>. While your view, for example, updates its text, color or touch interactivity.</p><p><strong>requestLayout() —</strong>Called to update your view using <a href="https://developer.android.com/reference/android/view/View#onMeasure(int,%20int)"><strong>onMeasure(</strong></a><strong>)</strong>, after your view updates, it changed its size and you need to measure it once again to draw it depending on the new size.</p><h3>Conclusion</h3><p>Generally, usage of existing views present in the Android is advisable. But if you want your customized view to use in your UI, then creating your custom view is too direct. Here, I covered only the basic concept of custom views in Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*XBZJi4zi2yllZc6j" /></figure><p>Take a look at the <a href="https://developer.android.com/guide/topics/ui/custom-components">link</a> to get more details to create more interactive and optimized custom views.</p><p>Thanks for reading!</p><p>Clap on it, if you like it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4abd8f63918d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViewModel using Retrofit — MVVM Architecture]]></title>
            <link>https://medium.com/@ronak./viewmodel-using-retrofit-mvvm-architecture-f759a0291b49?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f759a0291b49</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Fri, 03 Apr 2020 21:48:50 GMT</pubDate>
            <atom:updated>2020-06-10T05:13:48.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>ViewModel using Retrofit — MVVM Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*216ZINbPchgFI_Qj.gif" /></figure><p>MVVM is the architectural pattern in the development that provides the solution to separate the UI logic and business logic. It targets the easier management of UI code and app logic.</p><blockquote>Three Main Components of MVVM Architecture are:</blockquote><p><strong><em>Model, View, and ViewModel</em></strong></p><figure><img alt="It shows how all the modules should interact with one another after designing the app." src="https://cdn-images-1.medium.com/max/960/0*Ue9tnmHvGhCJpJ4Q.png" /><figcaption>Flow Diagram of MVVM Architecture</figcaption></figure><p><strong><em>Model</em></strong> responds to <strong>business logic</strong>, <strong><em>View</em></strong> is that the <strong>interface</strong> and <strong><em>ViewModel</em></strong> mediate <strong>View</strong> access to <strong>Model</strong>.</p><p><strong>Model —</strong></p><p>A model contains the data and business logic of the app. Among the implementations of this is often to show its data through observable. <strong>LiveData</strong> doesn’t affect the lifecycle of other app components, like activities and fragments. Here, we use LiveData within the <strong>Repository class</strong>.</p><p><strong>View —</strong></p><p>Only user interaction i.e.XML, no business logic.<em> </em>It actually has no idea by whom or how that data will be consumed. Only Activity holds the reference to ViewModel and not vice versa, this solves our tight coupling issue.</p><p><strong>ViewModel —</strong></p><p>The ViewModel class is meant to store and manage UI-related data during a lifecycle conscious way. The ViewModel class allows data to survive configuration changes like screen rotations. You can also use a ViewModel to share data between fragments. It is a part of the lifecycle library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZRQJmy_LHVr1XHaXW2IVEA.png" /></figure><blockquote><strong>Add Dependencies on build.gradle file:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e65f2d4cdb666896fa7224e91665722c/href">https://medium.com/media/e65f2d4cdb666896fa7224e91665722c/href</a></iframe><blockquote><strong>Create a Model Class for API Response:</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/802cd9d17de93654cfddd3d30e7eac12/href">https://medium.com/media/802cd9d17de93654cfddd3d30e7eac12/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5a0de899897610e283036f394fa7e0/href">https://medium.com/media/7f5a0de899897610e283036f394fa7e0/href</a></iframe><blockquote><strong>Retrofit Service Class for creating services —</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7112f66c72eaebf041bf3d5ff48fae04/href">https://medium.com/media/7112f66c72eaebf041bf3d5ff48fae04/href</a></iframe><blockquote><strong>Make Repository Class —</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd36b54b15e6958bad9a6365b0c19afc/href">https://medium.com/media/dd36b54b15e6958bad9a6365b0c19afc/href</a></iframe><blockquote><strong>Make ViewModel class —</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed09abf22b9ec099da44c085823fc4d/href">https://medium.com/media/7ed09abf22b9ec099da44c085823fc4d/href</a></iframe><blockquote><strong>MainActivity</strong> class where we use <strong>ViewModel</strong> for observing data —</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc3dcac7fac9d584693d1b8fea8ab6f/href">https://medium.com/media/5dc3dcac7fac9d584693d1b8fea8ab6f/href</a></iframe><p>That’s how we implement MVVM Architecture for Retrofit.</p><p>Thanks for reading.</p><p>Clap on it, if you like!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f759a0291b49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widgets]]></title>
            <link>https://medium.com/@ronak./widgets-f9b83eedcf35?source=rss-16c56702981d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b83eedcf35</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-widget]]></category>
            <dc:creator><![CDATA[Ronak Sethi]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 05:09:54 GMT</pubDate>
            <atom:updated>2020-04-19T23:22:46.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android App Widgets</h3><p>A widget is a gadget or a way to control your android application. Widgets are basically a shortcut to your favorite applications by placing them on the home screen. Some of the common widgets are — music widget, weather widget, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bze-jsBbJQ12He5U.jpg" /><figcaption>An Example of an App Widget</figcaption></figure><p>Widgets are of many types — information widgets, collection widgets, hybrid widgets, and control widgets. Android gives the feature to design and manage those widgets efficiently.</p><p><strong>To create an App Widget, you need the following:</strong></p><p><strong>AppWidgetProviderInfo object</strong>: It contains the metadata of an app widget, as its layout, update frequency, and class for the provider (AppWidgetProvider class).</p><p><strong>AppWidgetProvider class implementation:</strong> It defines and consists of the basic methodology that allows you to communicate with the widget, based on events. It provides an update when the app widget is enabled, disabled, updated and deleted.</p><p><strong>View layout</strong></p><p>The basic layout for the app widget, designed in XML.</p><p><strong><em>Declaring an App Widget in the Manifest</em></strong><br>We have to first declare the AppWidgetProvider class in your application’s AndroidManifest.xml file. For example:</p><pre>&lt;receiver android:name=&quot;ExampleAppWidgetProvider&quot; &gt;<br> &lt;intent-filter&gt;<br>     &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt;<br>     &lt;/intent-filter&gt;<br> &lt;meta-data android:name=&quot;android.appwidget.provider&quot;<br> android:resource=&quot;@xml/example_appwidget_info&quot; /&gt;<br>&lt;/receiver&gt;</pre><p>The &lt;receiver&gt; element requires the android:name attribute, which specifies the AppWidgetProvider used by the App Widget.</p><p>This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast.</p><p>The &lt;meta-data&gt; element specifies the AppWidgetProviderInfo resource and requires the following attributes:</p><p><strong>android:name — </strong>It gives the metadata name for the widget. We can identify the data using android.appwidget.provider.</p><p><strong>android:resource —</strong> It provides the AppWidgetProviderInfo location.</p><p>Methods defined in this class for App Widgets —</p><ul><li>onDeleted(Context context, int[] appWidgetIds)</li><li>onDisabled(Context context)</li><li>onEnabled(Context context)</li><li>onReceive(Context context, Intent intent)</li></ul><p><strong>Set the Widget in the configuration manifest.</strong></p><pre>&lt;activity android:name=&quot;.ExampleAppWidgetConfigure&quot;&gt;<br> &lt;intent-filter&gt;<br>     &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_CONFIGURE&quot;/&gt;<br>     &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><p>Also, the Activity must be declared in the AppWidgetProviderInfo XML file, with the android:configure attribute. For example, the configuration Activity can be declared like this:</p><pre>&lt;appwidget-provider xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>     …<br>     android:configure=&quot;com.example.android.ExampleAppWidgetConfigure&quot;<br>     … &gt;<br>&lt;/appwidget-provider&gt;</pre><p><strong>Setting preview Image.</strong></p><pre>&lt;appwidget-provider xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>     …<br>     android:previewImage=&quot;@drawable/preview&quot;&gt;<br>&lt;/appwidget-provider&gt;</pre><p>That’s it by my side.</p><p>Clap on it, if you like it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b83eedcf35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>