<?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[BYJU’S Exam Prep Engineering - Medium]]></title>
        <description><![CDATA[The Most Comprehensive Preparation App for All Exams - Medium]]></description>
        <link>https://medium.com/gradeup?source=rss----94a8b21e6d41---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>BYJU’S Exam Prep Engineering - Medium</title>
            <link>https://medium.com/gradeup?source=rss----94a8b21e6d41---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:26:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/gradeup" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Comprehensive Guide To Using The New SplashScreen API]]></title>
            <link>https://medium.com/gradeup/a-comprehensive-guide-to-using-the-new-splashscreen-api-34cdbc9f37ca?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/34cdbc9f37ca</guid>
            <category><![CDATA[splash-screen]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[splashscreen-api]]></category>
            <dc:creator><![CDATA[yogesh]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 09:00:29 GMT</pubDate>
            <atom:updated>2022-08-25T09:00:29.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*SjQA1uB5jcS8dQHfXXaV7A.jpeg" /></figure><p>Hi, there! In this article we will learn how to build Android splash screen using SplashScreen API introduced in <strong>Android 12. </strong>We will be comparing the old way of adding a splash screen with the new way.</p><h4><strong>What is Splash Screen ?</strong></h4><p>Splash screen is the initial screen you’ll see when you open your app. It is also called as <strong>launch screen</strong> or <strong>start up screen</strong>. If the app while launching shows blank screen for a moment, it probably doesn’t have a splash screen.</p><h4><strong>Why is Splash Screen needed in apps ?</strong></h4><p>A good splash screen is a differentiator between a basic app and a professional one. Besides that, other reasons being:</p><ul><li>Android apps don’t launch very fast, especially for the first time. There is a delay where splash screen can really help you catch the attention of the user, thus it can be used for promoting the app and display your logo.</li><li>It can also be used to fetch data before users enters your home screen to give him a smoother experience.</li></ul><h4><strong>Why is there a need to use a new API ?</strong></h4><p>Up until now creating a splash screen was a tedious and required quite a bit of boilerplate code to be written like creating a new SplashScreenActivity, adding timers, handling data downloading, etc. It also slowed down the app. But now the new Splash Screen API allows one to avoid all that and helps create splash screens much more easily and efficiently.</p><h4><strong>How to add the splash screen API to your project?</strong></h4><ol><li>Change <strong>compileSdk to 31</strong> in the module level <em>build.gradle file and a</em>dd the SplashScreen API as a dependency to your project, using the compat library that wraps the API and provides back support for older versions of Android.</li></ol><pre>android {<br>   compileSdk 31<br>   ...<br>} <br></pre><pre>dependencies {<br>   ...   <br>  implementation &#39;androidx.core:core-splashscreen:1.0.0&#39;<br>}</pre><p>2. Create a new Theme (e.g Theme.App.Starting) and set its parent to <em>Theme.SplashScreen</em> or <em>Theme.SplashScreen.IconBackground</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFFa8sv4Fd5r5n7j6QLrcQ.png" /></figure><ul><li>Point 1 represents the icon of the screen. (windowSplashScreenAnimatedIcon)</li><li>Point 2 represents the background colour of the splash screen icon. (windowSplashScreenIconBackgroundColor)</li><li>Point 3 represents the background colour of the splash screen .(windowSplashScreenBackground)</li><li>Point 4 represents the space for branding logo if needed.(windowSplashScreenBrandingImage)</li></ul><pre>&lt;style name=&quot;LauncherTheme&quot; parent=&quot;Theme.SplashScreen&quot;&gt;<br> <br>   &lt;item name=&quot;windowSplashScreenBackground&quot;&gt;@color/splashColor&lt;/item&gt;<br> <br>   &lt;item name=&quot;windowSplashScreenAnimatedIcon&quot;&gt;@drawable/splash_icon&lt;/item&gt;</pre><pre>&lt;item name=&quot;windowSplashScreenAnimationDuration&quot;&gt;300&lt;/item&gt;</pre><pre>&lt;item name=&quot;windowSplashScreenBrandingImage&quot;&gt;@drawable/brandingIcon&lt;/item&gt;</pre><pre>    &lt;item name=&quot;postSplashScreenTheme&quot;&gt;@style/LaucherTheme&lt;/item&gt;</pre><pre>&lt;/style&gt;</pre><ul><li><em>windowSplashScreenBackground</em>: Background color of the splash screen. Defaults to the theme’s ?attr/colorBackground. It specifies solid colour for window background.</li><li><em>windowSplashScreenAnimatedIcon:</em> Replaces the icon in the center of the screen and doesn’t need to be animated. Default icon is app’s launcher icon.</li><li>windowSplashScreenAnimationDuration: splash screen icon<em> </em>can be both static and animated. thus duration is required to specifiy how long the animation should be shown on the screen. The recommended duration for app icon animation is that it shouldn’t exceed 1000 milliseconds.</li><li>windowSplashScreenBrandingImage: it can be used to set an image to be shown at the bottom of the splash screen. The design guidelines recommend against using a branding image</li><li><em>postSplashScreenTheme</em>: It specifies the theme of the activity that follows the splash screen immediately. It’ll be the theme of your home screen.</li></ul><p>3. Open AndroidManifest file and add a theme to the activity.</p><pre>&lt;activity<br>    android:name=&quot;.view.activity.HomeActivity&quot;<br>    android:theme=&quot;@style/LauncherTheme&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>        &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><p>4. To use the splash screen features, call <strong>installSplashScreen</strong>() method <strong>before super.onCreate() </strong>within the activity which starts immediately after the splash screen. In our case, it is HomeActivity.</p><pre>class HomeActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {           <br>        installSplashScreen()<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>    }<br>}</pre><p>5. build and run 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*u4I-jL2Xg1ttDVtb4BDulw.jpeg" /></figure><p><strong>Performance Improvement</strong></p><p>Startup Time can be measured by using Time to initial display metric from logcat. Logcat includes an output line containing a value called <em>Displayed</em>. This value represents the amount of time elapsed between launching the process and finishing drawing the corresponding activity on the screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6lfVHiPxyRV-Pb-L6TSsQ.png" /></figure><p>old avg startup time: 1m 106 ms</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB6bDVsXizTa3EDLoDekiQ.png" /></figure><p>new avg startup time: 625ms</p><p>So using the new splash screen api we got ~2x faster startup time in android 12 devices.</p><p><strong>Some Useful links</strong></p><ul><li>Specs for splash screen icons : <a href="https://developer.android.com/reference/kotlin/androidx/core/splashscreen/SplashScreen#specs">link</a></li><li>Migrate from old splash screen : <a href="https://developer.android.com/guide/topics/ui/splash-screen/migrate">link</a></li><li>Measure the startup time to imporve performance: <a href="https://developer.android.com/topic/performance/vitals/launch-time#time-initial">link</a></li></ul><p><strong>Things I disliked about the api.</strong></p><ul><li><em>windowSplashScreenBackground </em>supports only single colour and there is no support to add drawable yet.</li><li>There is no fixed guidelines for the image which makes it more of a hit and error game. You can only try adding padding to the image until it fits.</li><li>There is no splash screen icon displayed when using deeplinks or notifications</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34cdbc9f37ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/a-comprehensive-guide-to-using-the-new-splashscreen-api-34cdbc9f37ca">A Comprehensive Guide To Using The New SplashScreen API</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding/Replacing Cassandra Nodes, You might wanna cleanup]]></title>
            <link>https://medium.com/gradeup/adding-replacing-cassandra-nodes-you-might-wanna-cleanup-760161dedc2f?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/760161dedc2f</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[nodetool]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cassandra]]></category>
            <dc:creator><![CDATA[Himanshu Agrawal]]></dc:creator>
            <pubDate>Fri, 13 May 2022 10:46:11 GMT</pubDate>
            <atom:updated>2022-05-13T10:46:11.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adding/Replacing Cassandra Nodes: you might wanna cleanup!</h3><p><em>Nodetool, a must-have for those managing Cassandra in production!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ga8MSYkqSlMskK_znBXp0w.jpeg" /><figcaption>Source: <a href="https://www.earthday.org/">earthday.org</a></figcaption></figure><p>Well, if you are running a Cassandra cluster, you should certainly go through <strong>nodetool</strong> features. That is what helped me save lots of disk space.</p><p>Since you are managing a Cassandra cluster, there would have been times when you scaled up on the number of nodes in your cluster, or when you might have even replaced an old node with a new node. It&#39;s common, and we at <strong>BYJU’s Exam Prep</strong> had also been doing the same until we realized that our disk space is growing continuously and that we needed to scale up disk space as well.</p><p><em>Easy! I could go ahead and change the disk from 1 TB to 2 TB. I might end up with a few storage costs, but who cares!</em></p><p>Well, it turns out the bigger your disk size, the more time it takes to boot up when you restart your cluster. As the DB engine boots up, it has to gain control of all the SSTables and all the commit logs; so the data it has to operate on is huge and so it takes time.</p><p>Something else we noticed was that the older nodes have a huge amount of data whereas the new nodes had comparatively little data. So one might think of rebalancing the nodes!</p><p><em>Do you need to?</em></p><h3>Here’s what we did:</h3><blockquote><a href="https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/tools/toolsCleanup.html">nodetool cleanup</a></blockquote><p>That&#39;s pretty much it! We just ran cleanup! It took somewhere around 18–20 hours for us, but the results were impressive.</p><h3>When do you need it?</h3><ul><li>When we add a new node to the cluster, Cassandra moves a few partition ranges from each node to the new node. But it does not automatically remove the keys from the original node which are no longer in use. This created all the mess. I am sure the developers at Cassandra had significant reasons not to remove the discarded keys from the node; one I can think of is to prevent data loss in replicating the partitions.</li><li>This also happens when you decrease the replication factor, of course because partitions belonging to the replica that you just disowned are lying around on various nodes.</li><li>Another cause can be when you move the tokens, which might not be a normal scenario, so let us just skip this.</li></ul><p>If you perform any of the above operations, you must run a cleanup.</p><h3>How it worked for us</h3><p>Here’s a graph of Disk Space Used by one of our Cassandra nodes. But first, how did we end up in such a scenario.<br>We had a 3 node cluster of 1 TB each &amp; for some reason, we replaced two of the nodes with new ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nik78pR9KkHhvwoW2TrhRQ.png" /></figure><p>The difference as you can see is huge, from 824GB to 504GB on the node that we didn’t replace. Well, it was expected, considering we replaced 2/3rd of the nodes.</p><h3>Considerations before cleanup</h3><p>The node you are about to run cleanup on will require excessive CPU resources in the process. Before running it in production, make sure to find a suitable time period with low traffic, or have sufficient nodes in the cluster to handle read/write ops and avoid downtime. Also, since you don’t know how long it’s gonna take, you can use a detachable session or run the command in background (<a href="https://github.com/tmux/tmux/wiki"><em>tmux</em></a>).<br>For us, our traffic drops significantly during night hours, so that was a plus point for us. Also under normal circumstances, our CPU usage was around 20–30% which could easily provide room for cleanup to run its operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760161dedc2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/adding-replacing-cassandra-nodes-you-might-wanna-cleanup-760161dedc2f">Adding/Replacing Cassandra Nodes, You might wanna cleanup</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose: everything you need to know to get started]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Understanding the basics of Jetpack Compose and how it changes the way Android developers perceive the UI</p><p class="medium-feed-link"><a href="https://medium.com/gradeup/jetpack-compose-everything-you-need-to-know-to-get-started-2db13d248b0a?source=rss----94a8b21e6d41---4">Continue reading on BYJU’S Exam Prep Engineering »</a></p></div>]]></description>
            <link>https://medium.com/gradeup/jetpack-compose-everything-you-need-to-know-to-get-started-2db13d248b0a?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/2db13d248b0a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Faheem un nisa]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 12:10:44 GMT</pubDate>
            <atom:updated>2023-07-10T10:31:29.090Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[GraphQL, an alternate to Rest API]]></title>
            <link>https://medium.com/gradeup/graph-ql-an-alternate-to-rest-api-865b74302f48?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/865b74302f48</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Abhishek Tripathi]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 13:00:28 GMT</pubDate>
            <atom:updated>2021-07-18T15:37:14.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyY9VxBsWgAAVPdxmFpQYA.png" /></figure><p>Hello everyone! In this blog, we will learn about GraphQL in a very simple and concise way. After reading this blog, you will have a better understanding of what GraphQL is and why it is better than Rest API.</p><p>First, let’s try to understand some major problems with the rest API, then it will be easier to understand why GraphQL is better:</p><ul><li>Suppose you have a POST API which is giving you a large response and you need only two or three fields from that response. Yet, as we know, the entire response will be fetched which is not even required. The vice versa is also true. If, in the response, you have only two fields like <strong>user_name</strong> and <strong>address</strong> and, after a few days, you require few more fields then you need to discuss this with the backend developer to change the API structure accordingly.</li><li>When you working with REST than for fetch multiple data you need to hit multiple endpoints like, first of <strong>/api/users </strong>to get the data of users, second of <strong>/api/posts</strong> to fetch posts, and third of <strong>/api/followers </strong>to fetch followers of that users. On the other hand when working with GraphQL you can fetch this concrete data in single query like below:</li></ul><p><strong>Query:</strong></p><pre>query<br>{<br>    User(id: &quot;1004&quot;)<br>    {<br>      name<br>             posts<br>             {<br>             post_title<br>             }</pre><pre>             followers(last: 3)<br>             {<br>             name<br>             }<br>     }<br>}</pre><p><strong>Response:</strong></p><pre>{<br> &quot;data&quot;:{<br>     &quot;user&quot;:<br>          {<br>           &quot;name&quot;: &quot;Jack&quot;,<br>           &quot;posts&quot;: [<br>           {&quot;post_title&quot;: &quot;This is my first post&quot;}<br>           ],<br>           &quot;followers&quot;: [<br>           {&quot;name&quot;:&quot;Mock&quot;},<br>           {&quot;name&quot;:&quot;Rock&quot;},<br>           {&quot;name&quot;:&quot;Monus&quot;},<br>           ]<br>           }<br>        }<br>}</pre><p>There are few other problems also which we’ll discuss later in this blog. Now let’s understand what is GraphQL and how it has overcome these problems.</p><p><strong>What is GraphQL? :</strong></p><p>GraphQL is a query language provided by Facebook in 2015. It is not specific to any single platform. It works with all platforms like Android, iOS or Web.</p><p><strong>Advantages of GraphQL:</strong></p><ol><li>The main advantage of GraphQL is that it is very easy to learn and implement. Only few steps are required to implement it in any Android Application. One more advantage is that it is not specific to any application architecture.</li><li>You will only get what you want, no more and no less. You can see in the example below that you are getting only the data you are asking in the query.</li></ol><p><strong>Only title required:</strong></p><pre><strong><br></strong>{<br> todos <strong>{<br>     </strong>title<br> <strong>}<br></strong>}</pre><p><strong>Response:</strong></p><pre><strong><br></strong>{<br>“data”: {<br>    “todos”: [<br>            {<br>                “title”: “New Test”<br>               }<br>             ]<br>        }<br>}</pre><p><strong>Now if id is also required along with title then just add it in query.</strong></p><pre>{<br>   todos {<br>         title<br>         id<br>        }<br>}</pre><p><strong>Response:</strong></p><pre><strong><br></strong>{<br>“data”: {<br>   “todos”: [<br>      {<br>        “id”: 571<br>        “title”: “New Test”<br>         }<br>        ]<br>       }<br>}</pre><p>As you can see in the above example, if you are using GraphQL then whatever data you want you just need to add it in the query and you will get the desired response. Now you can compare this with the REST API and experience the advantage.</p><p><strong>3. Avoid Multiple API Calls: </strong>As we already discuss above, we can fetch multiple type data (<strong>user_data, post_data, followers</strong>) in single query.When you work with REST you need to hit three API for this.</p><p><strong>4. Less Dependency on Backend Developer:<br></strong>When you use GraphQL , for every change in the API structure, you don’t have to connect with the backend developer.</p><p><strong>5. </strong>Many free tools and extensions are available to write queries very easily and effectively.</p><h4><strong>Steps to implement:</strong></h4><p><strong>Step 1: </strong>Add Dependencies</p><p>Add below dependencies in the project level Gradle file.</p><pre>classpath &#39;com.apollographql.apollo:gradle-plugin:0.3.2&#39;</pre><p>Now go to the app level Gradle file and add the following lines on the top of it</p><pre>apply plugin: &#39;com.android.application&#39;<br>apply plugin: &#39;kotlin-android&#39;<br>apply plugin: &#39;kotlin-android-extensions&#39;<br>apply plugin: &#39;com.apollographql.android&#39; (Add This one)</pre><p>Now inside dependencies add the following:</p><pre>implementation &#39;com.apollographql.apollo:apollo-runtime:0.3.2&#39;<br>implementation &quot;com.apollographql.apollo:apollo-android-support:0.3.2&quot;</pre><p><strong>Step 2: Download the schema</strong></p><p>Schema file defines the structure of your entire data and it also helps in writing queries.</p><blockquote>To download the schema first install apollo-codegen</blockquote><ul><li>npm-install apollo-codegen //For installing the apollo-codegen</li><li>apollo-codegen download-schema <a href="http://yourserver/graphql--output">http://yourserver/graphql--output</a> /Users/Abhishek/Desktop/GraphqlFiles/schema.json</li></ul><p><strong>Step 3: Create your query</strong></p><pre><strong>query</strong> FindToDo($toDoId:String!){<br>    todos(todoId:$todoId) {<br>            created_at<br>            id<br>            title<br>            user<br>      }<br>   }</pre><p>Now create a folder with the name “graphql” under the /main of your project and copy both file schema and query file to this folder. Then rebuild your project and you will get auto generated model against your query in build/generated.</p><p><strong>Step 4:</strong></p><p>Now it’s time to setup the apollo client</p><pre>private fun setupApollo(): ApolloClient {<br>    val okHttp = OkHttpClient<br>        .Builder()<br>        .addInterceptor(<strong>{ </strong>chain <strong>-&gt;<br>            </strong>val original = chain.request()<br>            val builder = original.newBuilder().method(original.method(),<br>                original.body())<br>            builder.addHeader(&quot;Authorization&quot;<br>                , &quot;Bearer &quot; + BuildConfig.AUTH_TOKEN)<br>            chain.proceed(builder.build())<br>        <strong>}</strong>)<br>        .build()<br>    return ApolloClient.builder()<br>        .serverUrl(BASE_URL)<br>        .okHttpClient(okHttp)<br>        .build()<br>}</pre><p>You have added all the dependencies like <strong>header</strong>, <strong>base_url</strong> to your apollo client. Now just use this apollo client to hit the query you write and get the response like below:</p><pre>client=setupApollo()<br>client.query(FindQuery    <em>//From the auto generated class<br></em>.builder()<br>.todoId(model.gettoDoId()) <em>//Passing required arguments<br></em>.build())<br>.enqueue(object : ApolloCall.Callback&lt;FindQuery.Data&gt;() {<br>    override fun onFailure(e: ApolloException) {<br>        Log.info(e.message.toString())<br>    }<br>    override fun onResponse(response: Response&lt;FindQuery.Data&gt;) {<br>        Log.info(&quot; &quot; + response.data()?.repository())<br>        runOnUiThread(<strong>{<br>           //This is your required data</strong></pre><pre><strong>           </strong>textViewID.text<strong> = </strong>response.data()?.todos?.id()<br>           textViewTitle.text = response.data()?.todos?.title()<br>           textViewUser = response.data()?.todos?.user() <br>        <strong>}</strong>)<br>    }</pre><p>Setup your UI according to your requirement and your module is ready with the above steps.</p><p>Now let’s see what options you have in GraphQL like Get, Post, Put which we have in Rest Api:</p><ol><li><strong>Query: </strong>Query is just like Get api in Rest. When you just want to fetch the data from the server like we have done above.</li><li><strong>Mutation: </strong>Mutation is not different in terms of syntax from the Query but when we want any kind of modification at the backend like add any user data or update any user data then we use mutation.</li><li><strong>Subscriptions: </strong>When we want any kind of real-time update in the data like socket connection then we use Subscription.</li><li><strong>Fragment: </strong>When we want to share any piece of information between multiple Query then we use Fragment. You can understand fragments same as functions in programming which you write once and use anywhere.</li></ol><h4>Conclusion:</h4><p>In this blog, I have given you an overview of GraphQL. Now, it’s your time to explore more. Happy Coding!</p><h4>References:</h4><p><a href="https://hasura.io/learn/graphql/android/introduction/">https://hasura.io/learn/graphql/android/introduction/<br></a><a href="https://www.apollographql.com/docs/android/">https://www.apollographql.com/docs/android/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=865b74302f48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/graph-ql-an-alternate-to-rest-api-865b74302f48">GraphQL, an alternate to Rest API</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Kotlin Coroutines for Beginners]]></title>
            <link>https://medium.com/gradeup/introduction-to-kotlin-coroutines-for-beginners-8b1d2a41c008?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b1d2a41c008</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Vermasanchit]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 09:56:44 GMT</pubDate>
            <atom:updated>2021-06-01T09:56:44.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwEga_OskHThy2iKUez8-A.png" /></figure><h3>Introduction</h3><p>For almost all modern applications, <strong>Asynchronous Programming</strong> is very important. It allows performing heavy-duty tasks away from the UI thread, in the background paralelly. By doing this, you can avoid UI freezes, and make the user experience fluid.</p><p>Android provides several asynchronous programming tools like <strong>RxJava</strong>, <strong>AsyncTasks,</strong> <strong>Jobs</strong>, <strong>Threads </strong>but it’s difficult to find the most appropriate one to use. We basically started handling this using the <strong>callback</strong> mechanism. We do something like hitting an API and wait for the callback to get invoked where we process the result. But this can introduce a ton of code. Not only that, but the code can become unreadable, as you introduce more callbacks.</p><p>If you’ve worked with Rx, exploring its list of operators in-depth while performing complicated operations and apply them correctly. On the other hand, AsyncTasks and Threads can easily introduce leaks and memory overhead.</p><p>Now we have another tool to write asynchronous code more naturally, which is more humanly understandable and readable: <strong>Kotlin Coroutines!</strong></p><h3>What are Coroutines?</h3><p><strong>Coroutines = Co + Routines</strong></p><p>Here, <strong>Co</strong> means <strong>cooperation</strong> and <strong>Routines</strong> means <strong>functions.<br></strong>According to documentation coroutines are nothing but <strong>lightweight threads</strong>.<br>The thing to remember is :</p><p><strong>Coroutines do not replace threads, it’s more like a framework to manage it.</strong></p><p>A framework to manage concurrency in a more performant and simple way with its lightweight thread which is written on top of the actual threading framework to get the most out of it by taking the advantage of cooperative nature of functions.</p><p>There is a number of important differences that make their real-life usage very different from threads, like :</p><ul><li>they are <strong>executed inside of a thread</strong>, so you can start many coroutines inside a single thread</li><li>coroutines are <strong>suspendable</strong> which means we can execute some instructions, pause the coroutine in the middle of execution and let it continue when we wanted to.</li><li>they can easily <strong>change the context</strong> which means that a coroutine that was started in one thread can easily switch to another thread</li></ul><p>Before diving in further, let’s look at some basic terminology for the Kotlin Coroutines:</p><ul><li><strong>Suspending functions:</strong> This kind of function can be suspended without blocking the current thread. Instead of returning a simple value, it also knows in which context the caller suspended it. Using this, it can resume appropriately, when ready.</li><li><strong>CoroutineBuilders:</strong> These are functions that help us create a coroutine. They can be called from normal functions because they do not suspend themselves. There are a bunch of coroutine builders provided by Kotlin Coroutines, including <strong>async(), </strong><strong>launch(), </strong><strong>runBlocking</strong>.</li><li><strong>CoroutineScope:</strong> Helps to define the lifecycle of Kotlin Coroutines. It can be application-wide or bound to a component like the Android Activity. You have to use a scope to start a coroutine.</li><li><strong>CoroutineDispatcher:</strong> Defines thread pools to launch your Kotlin Coroutines in. There are majorly 4 types of Dispatchers: Main, IO, Default, Unconfined.</li></ul><h3>Suspend Functions</h3><p>The <strong>suspend functions</strong> are not any special kind of functions they are just normal functions appended with the <strong>suspend </strong>modifier to have the superpower of suspending. It allows coroutines to be lightweight and fast because they don’t really cause any overhead, such as threads. Instead, they use predefined resources and smart resource management.</p><pre>suspend fun doNetworkCall(){</pre><pre>//write your code here</pre><pre>}</pre><p>These kinds of functions can be <strong>suspended</strong> <strong>without blocking the current thread</strong> and later can be resumed. Like in the image given below <strong>FunctionA</strong> is suspended while <strong>FunctionB</strong> continues the execution in the same thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*bMwilk_CSD6bfdkt.png" /></figure><p>The most important thing about suspend functions is that <strong>they can only be executed within another suspend function or a coroutine.</strong></p><pre>GlobalScope.launch{<br>   doSomething()<br>}<br>//////OR//////</pre><pre>suspend fun showUsersList(){   doSomething() }</pre><pre>suspend fun doSomething(){ <br>    //your code<br>}</pre><h3>Coroutines Builders</h3><p>Coroutine builders are simple functions that can create a coroutine around coroutine scopes. <strong>launch</strong>, <strong>async</strong>, <strong>runBlocking</strong> are some of the builders given by the library.</p><ol><li><strong>launch:</strong> it starts a new coroutine that is “<strong>fire and forget</strong>” — that means it won’t return the result to the caller.</li><li><strong>async: </strong>it returns a special kind of result called <strong>Deferred</strong> which can be cancelled or its result can be awaited using await().</li><li><strong>runBlocking:</strong> it is used to run tasks by blocking whichever thread it’s called on until the block completes.</li></ol><pre>val job = GlobalScope.launch { <br>    // fire and forget task is done here<br>}<br>____________________________________________________________________</pre><pre>GlobalScope.launch(Dispatchers.Main) {</pre><pre>val deferredJob1 = async{  <br>        // a job which returns some result <br>        function1()<br>    }<br>    val deferredJob2 = async{  <br>        // a job which returns some result <br>        function2()<br>   }</pre><pre>// here function1() and function2() will execute parallelly<br>    // block until deferredJob returns with the result <br>    val result = deferredJob1.await()</pre><pre>}<br>____________________________________________________________________</pre><pre>runBlocking {</pre><pre>// block the calling thread until this block execution isn&#39;t<br>    complete</pre><pre>}</pre><h3>Switching Context</h3><p>Sometimes while doing a task, we may need to do some <strong>IO</strong> operation, then some DB operation or some kind of computation, and then end with showing some UI on <strong>Main</strong> thread. This requires us to jump between correct dispatchers.</p><p>To do this coroutines provide us <strong>withContext()</strong> operator. Using this we can switch to a different dispatcher and then come back to the old dispatcher as its block ends.<br>Remember, calling <em>withContext</em> will suspend the calling function until the withContext block doesn’t end.</p><pre>val job = GlobalScope.launch(Dispachers.IO) { <br>    doNetworkCall()<br>    withContext(Dispatcher.Main){<br>        //update ui here<br>    }<br>}</pre><h3>Coroutine Scope</h3><p><strong>Scope</strong> in which a coroutine runs (similar to variable scope). When the scope ends, so does the coroutine. When a child coroutine is started inside a parent one it <strong>inherits parent scope</strong> (Unless specified otherwise). It means that when the parent coroutine is stopped, so will the child coroutine since its scope was that of the parent.</p><p>There are mainly 3 types of coroutine scope:</p><ul><li><strong>Global Scope:</strong> GlobalScope is alive as long as your app is alive, if you doing some counting for instance in this scope and rotate your device it will continue the task/process.</li></ul><pre>GlobalScope.launch{<br>   fetchData()<br>}</pre><p>Since it is alive as the application is alive, it may produce memory leaks. For example, if there are 2 activities Activity1 and Activity2, you move to Activity2 and make a network call in a GlobalScope. But before completing the network call you moved back to Activity1. Now, since the GlobalScope is alive throughout the application, it will not cancel the call and produce a memory leak.</p><ul><li><strong>ViewModel Scope:</strong> A ViewModelScope is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically cancelled if the ViewModel is cleared. Under the hood, it uses a <strong><em>CoroutineContext</em></strong> with <strong><em>SupervisorJob</em></strong> and <strong><em>Dispatchers.Main</em></strong>. When the ViewModel is cleared, it executes the clear method before calling onCleared. In the clear method, the ViewModel cancels the Job of the <strong><em>viewModelScope</em></strong>.</li></ul><pre>viewModelScope.launch{<br>   fetchData()<br>}</pre><ul><li><strong>LifeCycle Scope: </strong>A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is cancelled when the Lifecycle is destroyed.</li></ul><pre>lifecycleScope.launch{<br>   fetchData()<br>}</pre><ul><li><strong>CoroutineScope </strong>— This allows you to define a custom scope by providing your own context.</li></ul><pre>val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())<br>scope.launch{<br>   fetchData()<br>}</pre><h3>Coroutine Dispatcher</h3><p>Dispatchers determine what thread or thread pool the coroutine uses for execution. The dispatcher can confine a coroutine to a specific thread. It can also dispatch it to a thread pool. We have mainly 3 types of dispatcher — <strong>Main</strong> (thread), <strong>IO</strong> (thread pool), <strong>Default</strong> (thread pool).</p><ul><li><strong>Dispatchers.Default:</strong> CPU-intensive work, such as sorting large lists, doing complex calculations, and similar. A shared pool of threads on the JVM backs it.</li><li><strong>Dispatchers.IO:</strong> networking or reading and writing from files. In short — any input and output, as the name states</li><li><strong>Dispatchers.Main:</strong> recommended dispatcher for performing UI-related events. For example, showing lists in a RecyclerView, updating Views and so on.</li></ul><pre>GlobalScope.launch(Dispatchers.Default){<br>   fetchData()<br>}</pre><pre>GlobalScope.launch(Dispatchers.IO){<br>   fetchData()<br>}</pre><pre>GlobalScope.launch(Dispatchers.Main){<br>   fetchData()<br>}</pre><p><strong>There is another type of dispatcher</strong></p><p><strong>Dispatchers.Unconfined:</strong> This dispatcher doesn’t confine coroutines to any specific thread. The coroutine starts the execution in the inherited CoroutineDispatcher that called it. But after a suspension ends, it may resume in any other thread.</p><p><em>Note that it’s an advanced mechanism that can be helpful in certain corner cases but, as stated in the official docs, it should not be used in general code.</em></p><h3>Coroutine Job</h3><p>To better manage a Coroutine, a job is provided when we launch (or async etc). When you launch a coroutine, you basically ask the system to execute the code you pass in, using a lambda expression. That code is not executed immediately, but it is, instead, inserted into a queue. A Job is basically <strong>a handle</strong> to the coroutine in the queue. It only has a few fields and functions, but it provides a lot of extensibility. Some functions out of many that job interface offers are as follows:</p><pre>val job = GlobalScope.launch(Dispatchers.Default) {</pre><pre>val job1 = launch{networkCall1()}<br>    val job2 = launch{networkCall2()}<br>}</pre><ul><li><strong>join() </strong>function is a suspending function, i.e. it can be called from a coroutine or from within another suspending function. Job blocks all the threads until the coroutine in which it is written or has context finished its work. Only when the coroutine gets finishes, lines after the join() function will get executed.</li><li><strong>cancel() </strong>method is used to cancel the coroutine, without waiting for it to finish its work.</li></ul><p>A job can go through the states: New, Active, Completing, Completed, Cancelling, and Cancelled. We don’t have access to the states, but we can access the following properties: <strong><em>isActive</em></strong>, <strong><em>isCancelled</em></strong> and <strong><em>isCompleted</em></strong>.</p><p><strong>Jobs can be hierarchical (parent-child relationship)</strong></p><p>If a launch is triggered in another coroutine (under the same scope context), the job of the launch will be made the child job of the coroutine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/0*HkNVpN7dNRUqANSX.png" /></figure><p>Such a parent-child relationship will trigger some behaviours given below:</p><ol><li>if parent job cancel, children’s jobs are cancelled as well</li><li>if we cancel the child’s job, the parent’s job continues on.</li><li>when a child’s job throw error, the parent’s job is cancelled as well</li><li>when the parent’s job error out, the children’s job is cancelled</li></ol><p>This can be easily understood with the help of a diagram given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*ERs5s5V6-QD7BjY6.png" /></figure><p><strong>SupervisorJob:<br></strong> Children of a supervisor <strong>job can fail independently of each other</strong>. A failure or cancellation of a child does not cause the supervisor job to fail and does not affect its other children; so a supervisor can implement a custom policy for handling failures of its children.</p><h3>Exception Handling</h3><p>Exception handling in Kotlin Coroutines behaves differently depending on the <strong>CoroutineBuilder</strong> you are using. The exception may get propagated automatically or it may get deferred till the consumer consumes the result.</p><p>Here’s how exceptions behave for the builders you used in your code and how to handle them:</p><ul><li><strong>launch</strong>: The exception propagates to the parent and will fail your coroutine parent-child hierarchy. This will throw an exception in the coroutine thread immediately. You can avoid these exceptions with try/catch blocks or a custom exception handler.</li></ul><pre>CoroutineScope.launch(Dispatchers.Main) {<br>    try {<br>         doSomething()  <br>   }catch (exception: Exception) {<br>         Log.d(TAG, “$exception handled !”)<br>   }<br>}</pre><pre>///////OR////////</pre><pre>val exceptionHandler = CoroutineExceptionHandler {<br>   coroutineContext, exception -&gt; <br>   // handle exception<br>}</pre><pre>val topLevelScope = CoroutineScope(Job() + exceptionHandler)</pre><pre>topLevelScope.launch(exceptionHandler) { … }</pre><ul><li><strong>async</strong>: You defer exceptions until you consume the result for the async block. That means if you forgot or did not consume the result of the async block, through await(), you may not get an exception at all! The coroutine will bury it, and your app will be fine. If you want to avoid exceptions from await(), use a try/catch block either on the await() call or within async().</li></ul><pre>val deferredJob = GlobalScope.async {<br>    fetchData()<br>}</pre><pre><strong>try</strong> {<br>   val data = deferredUser.await()</pre><pre>}<strong>catch</strong> (exception: Exception) {<br>   Log.d(TAG, &quot;$exception handled !&quot;)<br>}</pre><h3>Few extra points about Coroutines</h3><ul><li><strong>withTimeOut():</strong> is designed to <em>cancel</em> the ongoing operation on timeout, which is only possible if the operation in question is cancellable.</li><li><strong>delay(): </strong>delays <strong>coroutine</strong> for a given time without blocking a thread and resumes it after a specified time.</li><li>We can make out <strong>own dispatcher</strong> by wrapping a single thread or thread pool</li><li><strong>Dispatchers</strong>.IO is limited to 64 <strong>threads</strong> or the <strong>number</strong> of cores by default.</li></ul><p>I hope this article helped you to get some knowledge about Kotlin Coroutines and how to use coroutines in your project.</p><p>Please let me know your suggestions and comments.</p><p>Thanks for reading :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1d2a41c008" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/introduction-to-kotlin-coroutines-for-beginners-8b1d2a41c008">Introduction to Kotlin Coroutines for Beginners</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection: Dagger-Hilt vs Koin]]></title>
            <link>https://medium.com/gradeup/dependency-injection-dagger-hilt-vs-koin-ab2f7f85e6c6?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/ab2f7f85e6c6</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <dc:creator><![CDATA[Ankit Raj]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 07:13:41 GMT</pubDate>
            <atom:updated>2021-06-01T07:13:41.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dependency injection from zero to hero with Koin and Hilt</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qemJTVM6laqwf2Ll6InAUA.png" /></figure><blockquote><strong>Topics</strong></blockquote><ol><li><a href="https://blog.yudiz.com/what-is-koin-kotlin-dependency-injection/#what"><strong>What is DI (dependency injection)?</strong></a></li><li><strong>Why Koin and Hilt</strong></li><li><a href="https://blog.yudiz.com/what-is-koin-kotlin-dependency-injection/#vs"><strong>Koin Vs Dagger</strong></a><strong>-Hilt</strong></li><li><a href="https://blog.yudiz.com/what-is-koin-kotlin-dependency-injection/#setup"><strong>Setting up Koin</strong></a><strong> and Hilt</strong></li><li><strong>Explanation</strong></li><li><a href="https://blog.yudiz.com/what-is-koin-kotlin-dependency-injection/#ex"><strong>Examples</strong></a><strong>.</strong></li></ol><h4>What is Dependency Injection?</h4><p>As we know that, S.O.L.I.D is one of the most significant acronyms in Oops concepts. Using SOLID principle in android development could be helpful and effective to follow the clean code principle. These five basic principles of oops design by <strong>Uncle Bob(Robert C. Martin).</strong>In<strong> SOLID,</strong> It is the fifth principle is Dependency Inversion. Dependency Injection is a design pattern used to implement inverse of control, meaning the flow of an application is inverted. We can create the dependent object outside of the class and provide those objects to the class in different ways. DI can help with, moving the creation and binding of the dependent objects outside of the class that depends on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*Nd1aRAjjIfY8M0Xjb1xBVw.gif" /></figure><p>Implementing DI provides you with the following advantages:</p><ul><li>Reusability of code</li><li>Ease of refactoring</li><li>Ease of testing</li></ul><h3>Why Koin and Dagger-Hilt?</h3><p>You can’t talk about dependency injection in Android without mentioning <strong>Dagger,</strong> right? Like every other Android developer, I’m a <strong>big</strong> sufferer of <strong>Dagger 2</strong>. It’s unnecessarily complicated, there are so many (confusing) ways of configuring it and it’s verbose.</p><p>If you are an Android developer, chances are you might have used Dagger, which, undoubtedly, is a great library to implement DI.</p><p>But android development is evolving rapidly; with Kotlin, we can write platform-agnostic code in a common module. Meaning the business logic can be written in a single module that can be used by all the supported platforms. We can’t use Dagger2 in Kotlin multi-platform projects. So I did some digging and found this cool, lightweight library called <strong>Koin</strong>(with multi-platform support). With less learning curve and boilerplate code, it seems better than Dagger2. Koin is written in pure Kotlin using functional resolution only: no proxy, no code generation, no reflection!</p><p><strong>And what about Hilt? </strong>Hilt is the new dependency injection framework <strong>built on top of Dagger.</strong> The aim is to reduce the boilerplate code required for Dagger and make dependency injection less painful.</p><h4>How Koin works ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*cOgTXbh1sNCdfoDD43r9EQ.png" /></figure><p>Koin works on a simple DSL model. Here we have to create a module first. In this module all the dependent objects are there, then we have to load one or more modules in Koin. Then, we are ready to use this object. Generally, we are loading the module into Koin in the application class by calling startKoin method, then we can inject the object wherever we want, this how the Koin works.</p><h3>Setting up Koin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*g6fmu7yMuYe0ojF3dNayEw.jpeg" /></figure><h3>Understanding Terminologies in Koin</h3><p>While working with Koin, there are few terminologies we need to understand before getting started.</p><ul><li><strong>module</strong> — it creates a module in Koin which would be used by Koin to provide all the dependencies.</li><li><strong>single</strong> — it creates a singleton that can be used across the app as a singular instance.</li><li><strong>factory</strong> — it provides a bean definition, which will create a new instance each time it is injected.</li><li><strong>get()</strong> — it is used in the constructor of a class to provide the required dependency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*HJrge-mKqjf8Ilz5CQ1kgw.jpeg" /></figure><p>Now, we will create <strong>API</strong>, <strong>model</strong>, <strong>repository</strong> packages inside the data layer. It will have files like. We will understand with the reference of this package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJwQlQhbDH8j4n89D-FZog.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s35PqqlHQ325OQ8Dawe8OA.jpeg" /></figure><p>Now, we will create a package <strong>di -&gt; module</strong> and inside it, we will create AppModule, ViewModelModule.</p><p>Inside AppModule first, we will create the functions we want to provide as dependencies. We will update the file like,</p><p>Here, to provide the dependency as a singleton instance we use <strong>single{}</strong> and inside it, we will pass the function which will return the dependency as an instance to be used across the app.</p><p>We are using <strong>get()</strong> here to pass the dependency to the constructor. Using get it will only provide the constructor whose instance is already been provided by Koin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1bMU-8DxkMkD2ZQLCUWAA.jpeg" /></figure><p>Here, AppRepository requires ApiInterface in the constructor which will be provided by the Koin here. Now, to pass the ApiInterface as a param, we need to provide it as well from the module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddVN160nxGZBBBPGi4raZw.jpeg" /></figure><p>Here, you can see we are not using single, and in place of that we are using viewModel and inside it, we resolve the dependencies which we are providing from viewModelModule.</p><p>Now, we are done providing the dependencies. Let us start now by injecting the dependencies.</p><p>Now, we need to create the instance of ViewModel in the GalleryFragment so the values passed in the constructor of the ViewModel are passed to it.</p><p>To pass the instance of ViewModel we will create a variable called GalleryViewModel like,</p><pre><strong>private</strong> val viewModel : GalleryViewModel by <strong>viewModel</strong>()</pre><p>Here,<strong> by viewModel() </strong>creates the instance for the ViewModel and it will also resolve the dependency required by it.</p><p>To initialize Koin in the project we will update the onCreate() of the application like,</p><pre>override fun <strong>onCreate</strong>() {<br>    <strong>super</strong>.onCreate()<br>    startKoin {<br>        androidContext(<strong>this@ImageSearchApp</strong>)<br>        modules(listOf(appModule, repoModule, viewModelModule))<br>    }<br>}</pre><p>All the instances of required dependency full fill by using koin on kotlin platform in an easy way.</p><p><strong>How Hilt Work?</strong></p><p>Before starting with Dagger-Hilt we need to understand Dagger basics. In this section, we will help you understand the Dagger and its terminologies.</p><p>Basically, to understand Dagger we have to understand the 4 major annotations,</p><ul><li>Module</li><li>Component</li><li>Provides</li><li>Inject</li></ul><p>To understand it better in a basic way, think module as a provider of dependency and consider an activity or any other class as a consumer. Now to provide dependency from provider to consumer we have a bridge between them, in Dagger, Component work as that specific bridge.</p><p>Now, a module is a class and we annotate it with @Module for Dagger to understand it as Module.</p><p>A component is an interface, which is annotated with @Component and takes modules in it. (But now, this annotation is not required in Dagger-Hilt)</p><p>Provides are annotation which is used in Module class to provide dependency and,</p><p>Inject is an annotation that is used to define a dependency inside the consumer.</p><p><strong>Same Project structure for Hilt that given above Pic.</strong></p><h3>Setting up Hilt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V93cjzZqX0TeW3-yOfSIOA.jpeg" /></figure><p>We will first update our Application class App like,</p><pre><strong>class</strong> <strong>ImageSearchApp</strong> : <strong>Application</strong>()</pre><p>and we will update the Manifest file like,</p><pre>android:name=&quot;.ImageSearchApp&quot;</pre><p>Now, to begin working with Dagger we need to annotate the application class with <strong>@HiltAndroidApp</strong>. The updated code will look like this,</p><pre><strong>@HiltAndroidApp</strong><br><strong>class</strong> <strong>ImageSearchApp</strong> : <strong>Application</strong>()</pre><p>If you are planning to use Dagger-Hilt in your app, the above mention step is a mandatory one. It generates all the component classes which we have to do manually while using Dagger.</p><p>In <em>AppRepository</em> we will pass <em>ApiInterface</em> in the constructor of the repository. <em>AppRepository</em> looks like,</p><pre><em>@Singleton<br>class AppRepository @Inject constructor(private val apiInterface: ApiInterface):ViewModel() {<br><br>    fun getSearchResult(query : String) =<br>        Pager(<br>            config = PagingConfig(<br>                pageSize = 20,<br>                maxSize = 100,<br>                enablePlaceholders = false<br>            ),<br>            pagingSourceFactory = {PagingSourceData(apiInterface,query)}<br>        ).liveData<br>}</em></pre><p>Now, if you can see we have passed <em>ApiInterface</em> in <em>AppRepository</em>. So, to inject everything in the constructor we also need to provide it using <strong>@Provide</strong> annotation in Dagger.</p><p>We will create a class ApplicationModule and annotate it with <strong>@Module. </strong>Using this annotation will make the dagger understand that this class is a module.</p><pre><strong>@Module</strong><br><strong>class</strong> <strong>AppModule</strong> { }</pre><p>Now, we will need to plug this module class into the specific component. In this case, we need to this at the application level so we will install it in ApplicationComponent like,</p><pre><strong>@Module</strong><br><strong>@InstallIn</strong>(ApplicationComponent::<strong>class</strong>)<br><strong>class</strong> <strong>AppModule</strong> {}</pre><p>Here, you can see that we have used <strong>@InstallIn</strong> annotation to install it in ApplicationComponent. ApplicationComponent is provided by Dagger-Hilt.</p><p>This means that the dependencies provided here will be used across the application. Let’s consider that we want to use at the activity level we install the module in,</p><pre><strong>@InstallIn</strong>(ActivityComponent::<strong>class</strong>)</pre><p>Similarly like ApplicationComponent/ActivityComponent, we have a different type of components like,</p><p>Now, inside <strong>AppModule</strong>, we will provide all the dependencies one by one and the updated code of ApplicationModule class</p><p>Now, since everything is set up, now we need to use/inject them into the Android classes. In our case, we need our activity to start using them.</p><p>So to make any Android class supported by Dagger-Hilt we use,</p><pre><strong>@AndroidEntryPoint</strong></pre><p>So, in our code, we will create another package <strong>ui,</strong> and inside it will create another sub-package called <strong>main</strong> which will have MainActivity, MainViewModel, and MainAdapter to show the list of users.</p><p>Now, we will add the AndroidEntryPoint Annotation in MainActivity like,</p><pre><strong>@AndroidEntryPoint</strong><br><strong>class</strong> <strong>MainActivity</strong> : <strong>AppCompatActivity</strong>() {}</pre><p>Here, <strong>@AndroidEntryPoint </strong>means Dagger-Hilt can now inject dependencies in this class.</p><p><strong>@AndroidEntryPoint</strong> annotation can be used in,</p><ol><li>Activity</li><li>Fragment</li><li>View</li><li>Service</li><li>BroadcastReceiver</li></ol><blockquote>Hilt currently only supports activities that extend <a href="https://developer.android.com/reference/androidx/activity/ComponentActivity">ComponentActivity</a> and fragments that extend androidx library <a href="https://developer.android.com/reference/androidx/fragment/app/Fragment">Fragment</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*qgtLTMS4Fs9acyfAp8pvrQ.jpeg" /></figure><h4>Impact on performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqd6tjtaNvv_4DO78yG0Hw.png" /></figure><p>There is some advantage of the fact that Koin does not generate any code: <strong>it has a much smaller impact on our built time</strong>. Dagger needs to use an annotation processor to scan our code and generate appropriate classes. It may take some time and it may slow down our build. On the other hand, because Koin <strong>resolves dependencies at runtime</strong> it has slightly <strong>worse runtime performance</strong>.</p><h3>Summary</h3><p>My goal here is not to tell you which one of those libraries to use. I used both Koin and Hilt in two different, quite big projects. To be honest, I think the decision of which one to choose, Dagger or Koin, is <strong>way less important than to just anything that allows you to write code that is clean, simple, and easy to unit test.</strong> And I think both these libraries fulfil this purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab2f7f85e6c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/dependency-injection-dagger-hilt-vs-koin-ab2f7f85e6c6">Dependency Injection: Dagger-Hilt vs Koin</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutines for beginners: the only article you’ll need to get started!]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/gradeup/coroutines-for-beginners-the-only-article-youll-need-to-get-started-3178929ca70d?source=rss----94a8b21e6d41---4"><img src="https://cdn-images-1.medium.com/max/2568/1*xbjDt6y6Ewl8CeXAeIQfqg.png" width="2568"></a></p><p class="medium-feed-snippet">When we shifted to Kotlin at Gradeup, we realised that the www was pretty unfriendly for a coroutine beginner- there was a lot of&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/gradeup/coroutines-for-beginners-the-only-article-youll-need-to-get-started-3178929ca70d?source=rss----94a8b21e6d41---4">Continue reading on BYJU’S Exam Prep Engineering »</a></p></div>]]></description>
            <link>https://medium.com/gradeup/coroutines-for-beginners-the-only-article-youll-need-to-get-started-3178929ca70d?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/3178929ca70d</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[launch]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Faheem un nisa]]></dc:creator>
            <pubDate>Sun, 02 May 2021 13:35:51 GMT</pubDate>
            <atom:updated>2023-07-10T13:00:13.263Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Implement Custom Logger in NextJs]]></title>
            <link>https://medium.com/gradeup/how-to-implement-custom-logger-in-nextjs-a0495cbfda53?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/a0495cbfda53</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[custom-logger]]></category>
            <category><![CDATA[logger]]></category>
            <category><![CDATA[console-log]]></category>
            <dc:creator><![CDATA[Mohit Agrawal]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 06:22:33 GMT</pubDate>
            <atom:updated>2021-03-31T06:22:33.360Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to implement a custom logger for a NextJs application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVSEg9cUEwrlH0p1uy2dJQ.gif" /></figure><p><strong>What is Logging?</strong><br>Logging in simple language means recording every data. A log is a bit of text that describes an action that happened in the application. As our codebase grows, the ability to effectively debug also increases.</p><p>So in this article, a logging approach would be covered that can be easily implemented in any javascript codebase.</p><p><strong>How logging helps us</strong><br>When we have good logging in place, it becomes easier for developers to see exactly what the code is doing. By enabling all logging messages, developers can follow through with the execution flow of any part of the program without needing to manually set the breakpoints. One can log anywhere there is a significant change in logic.</p><p>These logs are important to verify what the application did just before a bug happened so that we can gather extra information about that bug.</p><p>Wait, does that mean you can log anywhere in the code?<br>Well, This approach might sound ugly and make it seem like the code would be cluttered and unreadable.<br>There are various logging levels that help us segregate the logs.</p><p><strong>Logging Levels</strong><br>Below are JavaScript’s built-in logging methods:</p><ul><li>console.log() —<em> outputs the plain text.</em></li><li>console.trace() — <em>outputs the plain text along with the entire stack trace to know where exactly the message is emitted from.</em></li><li>console.warn() — <em>outputs the warnings typically with a yellow background.</em></li><li>console.error() — <em>outputs the errors typically with red background.</em></li><li>console.info() — <em>outputs the text typically with blue background.</em></li></ul><p><strong>Problem Statement</strong></p><ol><li>Sometimes developers unknowingly push logs in production which can lead to leakage of quite sensitive data of the application.</li><li>It decreases application performance as it uses some CPU cycles and other resources (memory, etc). So only put logs wherever required</li><li>Sometimes you would want to get all the logs for the page in order to debug and fix issues.</li></ol><p><strong>Suggested Approach</strong></p><p>In this approach, set a key and its boolean value ( in this illustration, debug = true ) in the query params of the URL. When the page gets refreshed or reloaded, read the value of debug from the params and based on the value and print the logs of the application if the key is present. This way helps to enable or disable the logs of the application.</p><p><strong>Steps to create a logger in your application:</strong></p><ol><li>Open <strong>pages/_app.js</strong> and add below lines of code.</li></ol><p>Create a global variable(<strong>areLogsEnabled</strong> in this case) to determine if logs have been enabled by the user or not. Update its value by checking the query params in the URL. Set its value to true only If debug is equal to true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903c46569641d70deba17cbc57a55ae4/href">https://medium.com/media/903c46569641d70deba17cbc57a55ae4/href</a></iframe><p>2. Create a new logger function under /helpers/logger.js</p><p>Create an <strong>IIFE</strong>(Immediately Executable Function Expression) that returns an object which contains different logging methods. These methods will only get executed only if the logs are enabled. Further, logs can also be custom styled in order to easily identify the category.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05924d1507d97b6054fc446fec9ab5e3/href">https://medium.com/media/05924d1507d97b6054fc446fec9ab5e3/href</a></iframe><p>3. Now all you need to do is import the logger function in your respective pages or components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bbb65ec1d261a6147259f0571b542f3/href">https://medium.com/media/2bbb65ec1d261a6147259f0571b542f3/href</a></iframe><p>NOTE: This approach will print the logs on the server-side as well as the client-side when debug=true is present in the query params. This is not the only approach, there are various other mechanisms to build a logging system for your application irrespective of the framework.</p><p>One can also disable console logs based on the environment conditionally.</p><blockquote>To check out the source code for the implementation click <a href="https://github.com/mohitagrawal1305/nextjs-custom-logger">HERE</a> and for the demo click <a href="https://nextjs-custom-logger.vercel.app/">HERE</a>. And To get more understanding about what NextJs is refer to this <a href="https://nextjs.org/">link</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0495cbfda53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/how-to-implement-custom-logger-in-nextjs-a0495cbfda53">How to Implement Custom Logger in NextJs</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Open Source CI/CD tool Drone using Docker Compose]]></title>
            <link>https://medium.com/gradeup/setting-up-open-source-ci-cd-tool-drone-using-docker-compose-631dd2701af7?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/631dd2701af7</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[drone-ci]]></category>
            <dc:creator><![CDATA[Himanshu Agrawal]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 14:49:56 GMT</pubDate>
            <atom:updated>2021-03-26T14:49:56.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>Installing Open Source CI/CD tool Drone using Docker Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVggDoOh5gEIYZME7QXZdw.jpeg" /><figcaption>Running Drone with Docker</figcaption></figure><p>There are various open-source CI/CD tools like <strong>Travis CI, Circle CI, Jenkins, Gitlab, Github Actions, Drone</strong>, etc, but comparing all features and licensing options (open source applications also may require licenses at times) , we chose to go with self-managed <a href="https://drone.io/">Drone</a> at <a href="https://medium.com/u/b591e4785fab">Gradeup</a>.</p><h3>Why we preferred Drone over others</h3><ul><li>It is open-source (although requires a license to run more than 5000 builds per month)</li><li>It is written in <strong>Go</strong> which is trending for its performance and low resource consumption</li><li>Ability to run on-demand workers in Kubernetes as Jobs (not officially supported by Drone for community users)</li><li>Simple &amp; Easy Configuration (we will come to it)</li><li>An easy option to create custom Plugins (much needed)</li></ul><h3>How we use Drone</h3><p>Initially, we deployed Drone in Kubernetes and set up auto-scaling of workers which was quite easy as per provided documentation. But months later, we started facing issues like some pipelines stuck in running state for days (even after the timeout). We suspected this might have been because of <strong>AWS Spot Instances</strong> being used. Later we decided to go with a <strong>single EC2 Instance</strong> running Drone server as well as Workers (limited no of workers). It works well on a single node (t2.large: 2 Core 8 GB Ram) and doesn’t add up much wait time in a developer’s day to day task; so we continued using EC2 without auto-scaling.</p><h3>Setting up Drone using Docker-Compose</h3><h4>Prerequisites</h4><ul><li>Install Docker and Docker Compose on Server</li><li>Get Github Client ID and Secret: Login to Github and visit <a href="https://github.com/settings/applications/new">register a new OAuth application</a>. Choose a name for your application (drone-ci). Provide Homepage URL as https://drone.example.com and authorization callback as <a href="https://drone.example.com/login.">https://drone.example.com/login.</a> You can also use public IP for testing purposes.</li><li>Point domain name to the Server IP (if using domain instead of IP)</li></ul><p>And that&#39;s all for prerequisites! Let’s now jump to the main crux which is a mere 5 minute task!</p><p>Create a docker-compose.yaml file with the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d33d24735248d3e5f2fa88d48a447a/href">https://medium.com/media/25d33d24735248d3e5f2fa88d48a447a/href</a></iframe><h4>Some points to note in this config:</h4><ul><li>To allow only members of a particular Github Organization to access the service, use <strong>DRONE_USER_FILTER</strong>. If you want to allow some other users as well, add a comma-separated list of usernames and organisation names</li><li>Drone-server is the main backend which listens for Triggers and schedules workers; drone-agent are workers that do the work you requested for</li><li>Never copy DRONE_SECRET and DRONE_RPC_SECRET from anywhere if copying the docker-compose or configs from any sites</li><li>DRONE_SECRET and DRONE_RPC_SECRET should be the same in drone-server and drone-agent</li><li>Setup DRONE_RUNNER_CAPACITY based on the number of CPU Cores available (although even 20–30 workers do work on a 4 core machine, we observed better performance limiting to 4 workers in parallel)</li><li>Go for a License if your usage exceeds the Open Source limit</li><li>Feel free to play around with the environment variables in local/staging env, but double-check config before going to production for Secrets and Public Access</li></ul><h3>Adding CI Pipelines in Git Repo</h3><p>To use Drone for CI/CD, we first need to activate the repository from the Drone dashboard, and by default, Drone looks for a .drone.yml file in the repository. We can change the name of CI file as well as timeout for pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*I-3TXE1qwMBPrFy5o5ME_A.png" /><figcaption>Repository settings for Drone CI</figcaption></figure><p>A CI configuration file can have multiple pipelines, and each pipeline can have one or multiple steps. Every step of a Pipeline runs based on certain conditions (if provided) and performs tasks it is configured for. Here is a sample config file. (Don&#39;t get scared away by the length of this file, I have tried to include all configuration options that you might need! :D )</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7f20a2a9d6e1470b68f29c09cd55f2/href">https://medium.com/media/af7f20a2a9d6e1470b68f29c09cd55f2/href</a></iframe><p>The example contains a single pipeline with two steps: one to build and publish a docker image to ECR, another to update build status on Github using a plugin drone-github-comment (completely optional step)</p><p>Secrets can be managed from the Drone dashboard per repository with the option to make it accessible by pull requests or not. Instead of using environment for all variables and data sent to the plugins (as used in example), drone has currently shifted to using <strong>settings </strong>to pass data into plugins, and any variables starting with <strong>DRONE_ </strong>are no more required to pass into plugins- they are made available to the plugins automatically by drone. Plugins configurations have also been updated on Drone Plugin Index with settings in place of environments.</p><h4>Some plugins that may be useful for your teams:</h4><ol><li><a href="http://plugins.drone.io/drone-plugins/drone-slack/"><strong>Slack Notification</strong></a><strong>:</strong> This plugin can be used to send pipeline status updates to Slack channels</li><li><a href="http://plugins.drone.io/drone-plugins/drone-ecr/"><strong>ECR</strong></a>: For teams using private repositories on AWS, docker builds can be pushed to ECR</li></ol><p>There are plugins to help in CD processes like <a href="http://plugins.drone.io/appleboy/drone-ssh/"><strong>SSH</strong></a><strong>, </strong><a href="http://plugins.drone.io/danielgormly/drone-plugin-kube/"><strong>Kubernetes</strong></a><strong>, </strong><a href="http://plugins.drone.io/jmccann/terraform/"><strong>Terraform</strong></a>, etc. The complete list of plugins can be found on the <a href="http://plugins.drone.io/">plugins index</a>.</p><p>At times, developers have some requirements which are not available in any plugins already out on Github; with Drone we can easily work this out because of a much simpler process to build and use a custom plugin. <a href="https://github.com/gradeup/drone-github-comment">Drone Github Comment</a> is one such plugin I tried building and it was super easy (as well as fun :D ), and there are many more created by various open-source contributors, just needs a little digging up Google for that!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631dd2701af7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/setting-up-open-source-ci-cd-tool-drone-using-docker-compose-631dd2701af7">Setting up Open Source CI/CD tool Drone using Docker Compose</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Multiple Theme Support in NextJs]]></title>
            <link>https://medium.com/gradeup/implementing-multiple-theme-support-in-nextjs-709e2258e529?source=rss----94a8b21e6d41---4</link>
            <guid isPermaLink="false">https://medium.com/p/709e2258e529</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[css-variables]]></category>
            <category><![CDATA[theming]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[dark-mode]]></category>
            <dc:creator><![CDATA[Vatsala Mittal]]></dc:creator>
            <pubDate>Thu, 25 Mar 2021 07:27:41 GMT</pubDate>
            <atom:updated>2021-03-25T07:33:04.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>Switching between dark mode and light mode</h3><p>Maximum approaches to implementing theme support are using the useDarkMode and ThemeProvider or Styled Components in Next.js. But what if there is a way to implement multiple themes without the need for extra libraries?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*e4lo_rLPoU8siQTUHWWEoQ.png" /></figure><p>This approach will let us know how to implement the Dark Mode for Next.js. The fundamental strategy can also be used with any SSR app. Click <a href="https://dark-mode-example.vercel.app/">HERE</a> to see the <a href="https://dark-mode-example.vercel.app/">DEMO</a> for the implementation</p><h3>Our requirements</h3><p>Here’s our set of criteria for this feature</p><ul><li>The user should be able to click a toggle to switch between Light and Dark mode.</li><li>The user’s preference should be saved, so that future visits use the correct color theme.</li><li>The site should not flicker on the first load, even if the user has selected a non-default color theme.</li></ul><h3>A workable solution</h3><p>Here’s our solution, at a high level:</p><ul><li>Use CSS variables for all of our stylings.</li><li>When we’re generating the HTML at compile-time, inject a &lt;script&gt; tag before all of our content (the page itself)</li><li>In that script tag, work out what the user’s color preferences are.</li><li>Update the CSS variables using JavaScript.</li></ul><h3>Getting Started</h3><p>This implementation is done using the tutorial setup provided by nextJs</p><pre>npx create-next-app nextjs-blog --use-npm --example &quot;https://github.com/vercel/next-learn-starter/tree/master/learn-starter&quot;</pre><p>First, move all the styling in one folder naming /css and create a custom folder to add styling for custom modules with naming convention component-name.module.css.</p><p>Create a directory theme in the /css folder. Add two files: _light-color.css and _dark-color.css Below is the snippet that shows how to add colors in these files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*5jqipCePE81SEua2iwjguA.png" /><figcaption><strong>_dark-colors.css</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*e3rtjuPMggSeRAMsJw_MQw.png" /><figcaption><strong>_light-color.css</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*ygKRYj_LHwSK-4cV4I_QZA.png" /><figcaption>styles.css</figcaption></figure><p>Using the var feature of CSS we can dynamically add colors and create custom classes which will help in providing multiple themes to an application. So with this var variable when your theme changes the variable value changes according to the theme.</p><h3>Implementation</h3><p>The first step is to create a file theme-options.js in your components folder which would contain variables for all the themes you want on the website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*ww4Jza-7Jqtm-Z7cSosp0g.png" /><figcaption>theme-options.js</figcaption></figure><p>Then we add a script that creates a minified version of our theme-colors which can be later used. Before running this script we create a directory /theme-css in our root so that the files can directly be added there.</p><p>Below is the script to minify our theme CSS. The file will be added to the root</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*lf2pMZJ9cizyMGY7UBLJ1Q.png" /><figcaption>write-theme-color.js</figcaption></figure><p>Create custom <a href="https://nextjs.org/docs/advanced-features/custom-app">_app.js</a> and <a href="https://nextjs.org/docs/advanced-features/custom-document">_document.js</a> files for this implementation.</p><p>The next step to achieve multi-theme is to create a cookie value name <strong>g-theme. </strong>This will let us know what type of theme we need our website to look at. In _app.js of the application add the following code snippet in the Main Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ggbXnM8visdZDSps71VSw.png" /></figure><p>In _document.js we create a <strong>themeMap</strong> that stores minified files for both light and dark colors. We pass the theme map in our Initial Props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*sy1Ax2Ekify9WYRPVUUUJw.png" /></figure><p>In our render function of _document.js, we find out which theme is currently active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*V7lDUeBNZjeIT_2D6yox2w.png" /></figure><p>Here as you can see we are storing the value in <strong>themeCss</strong> by accessing data from <strong>themeMap </strong>that are accessed from props that were added above.</p><p>Once you have data in <strong>themeCss</strong> we add a style tag in the body in _document.js and return the following code snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz4DS3MhIjzA_ENS6-eqkA.png" /></figure><blockquote>Note : To avoid <a href="https://nextjs.org/docs/advanced-features/automatic-static-optimization">Automatic Static Optimization</a> by Next js make sure to add getInitialProps in your _app.js. And if you have static page then try using <a href="https://nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration">Incremental Static Regeneration</a></blockquote><p>Now, all we need to do is create a button component that changes the theme-mode for the application. Import the component wherever the toggle button is needed. On click of the button, the setCookieValue(Custom function that adds cookies) function will be called and would set the value for cookie <strong>g-theme </strong>opposite of the currently set value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c409c71d41c459ef3c7d9d8f490e095/href">https://medium.com/media/0c409c71d41c459ef3c7d9d8f490e095/href</a></iframe><h3>Deployment</h3><ol><li>After all the files have been added and changed for themes. We will first run write-theme-colors.js. Add the command to run the script in package.json.</li><li>First, delete your node_modules and .next folder. The install the node modules again and create a production build.</li><li>After the production build is created. We start the server and run the write-theme-color.js script parallelly. Once the files have been created stop the server.</li><li>We start the server again and click on the button for switching to dark-mode. The page would reload and you will see the themeCss is embedded in the body tag is changed and colors have changed to values defined in _dark-mode.css.</li></ol><blockquote><em>To check out the source code for the implementation click </em><a href="https://github.com/Vatsala04/dark-mode-example"><em>HERE</em></a><em> and for the demo click </em><a href="https://dark-mode-example.vercel.app/"><em>HERE</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709e2258e529" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/implementing-multiple-theme-support-in-nextjs-709e2258e529">Implementing Multiple Theme Support in NextJs</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>