<?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 Deepanshu on Medium]]></title>
        <description><![CDATA[Stories by Deepanshu on Medium]]></description>
        <link>https://medium.com/@deepanshu42?source=rss-2dda604e8c19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ahNCTh530KBf-CFfWtS6nA@2x.jpeg</url>
            <title>Stories by Deepanshu on Medium</title>
            <link>https://medium.com/@deepanshu42?source=rss-2dda604e8c19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:41:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepanshu42/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[Courier: Reimagining How We Send Push Notifications]]></title>
            <link>https://medium.com/gojekengineering/courier-reimagining-how-we-send-push-notifications-3f690d5827b9?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f690d5827b9</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 07:13:08 GMT</pubDate>
            <atom:updated>2023-10-23T07:13:08.215Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you need to know about Pusher, our dedicated service for sending push notifications.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kp9sF5umdEj5MJSXdVVNKA.jpeg" /></figure><p>Push notifications are an integral part of the Gojek experience. We send around <strong>100 million</strong> push notifications every day across all applications. They are used to deliver important and time-sensitive messages to our users like order updates, chat messages, or prompt the user to take an urgent action. Gojek has its own dedicated service, named <strong>Pusher</strong>, for sending push notifications to all mobile apps like Gojek, GoBiz, GoPartner, and GoPay.</p><p>In this blog, we will talk about the traditional architecture of Pusher and how we redesigned it to be super-reliable.</p><h3>Motivation</h3><p>With the rapid growth in the Gojek user base i.e., customers, merchant partners, and driver partners, it has become very crucial to have a reliable mechanism for sending push notifications. The traditional way of sending them via Firebase Cloud Messaging(FCM) for Android and Apple Push Notification Service(APNs) for iOS isn’t sufficient anymore. So we needed a new way of sending push notifications which is quick and reliable.</p><h3>Use cases</h3><ul><li><strong>Customer order updates<br></strong>GoFood &amp; GoRide ordering flow heavily relies on push notifications for sending order updates to customers in real time.</li><li><strong>Merchant Ordering flow</strong><br>For the merchant app, a push notification is triggered for every new order and further order updates.</li><li><strong>Driver Bids<br></strong>GoFood &amp; GoRide order bids are sent to the driver app using push notifications.</li><li><strong>Chat messages<br></strong>All new chat messages are sent as push notifications to the customer app when the user is offline(app in the background).</li><li><strong>Campaigns<br></strong>Campaign notifications for an ongoing promotion are also sent as push notifications.</li></ul><h3>Traditional architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltDu9t7GZE-1EmqgiOxKcw.png" /></figure><p>Traditionally, the flow of sending push notifications looked like this —</p><ol><li>All Gojek services make an HTTP request to Pusher to send push notifications to the mobile apps.</li><li>Pusher makes a request to the token service to get details of all registered devices for a user.</li><li>Pusher enqueues a job on Kafka, which is picked up by one of the workers, and a push notification is triggered via FCM/APNs based on the OS type of user.</li></ol><p>But there is one problem with this setup — low reliability. The delivery rate for push notifications was in the window of 75–85% across all user segments i.e., driver, customer, merchant.</p><h3>The case for Courier</h3><p><a href="https://www.gojek.io/blog/introducing-courier-the-information-superhighway-between-mobile-server">Courier</a> is Gojek’s in-house solution, built for creating and maintaining long-running persistent connections between mobile apps and servers using the MQTT protocol. After taking upon ourselves the challenges of handling a variety of use cases ranging from sending food order updates to chat messages via Courier, we moved on to solving one more. This time it was about delivering Push Notifications via our own information superhighway.</p><p><a href="https://www.gojek.io/blog/introducing-courier-the-information-superhighway-between-mobile-server">Introducing Courier - The Information Superhighway Between Mobile &amp; Server - 5 min read</a></p><h3>Design Decisions</h3><p>Let’s discuss a few design decisions we made along the way.</p><ul><li><strong>Quality of Service(QoS) level</strong></li><li><strong>Fallback mechanism</strong></li><li><strong>Topic Structure</strong></li></ul><h4><strong>Single Events Source</strong></h4><p>The first decision was to choose the right <a href="https://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels/">QoS</a> for this task. QoS 0 is easy to implement but does not have an acknowledgment flow. QoS 1 retries publishing the message till an acknowledgment is received, this means there could be duplication. In QoS 2, the sender and receiver engage in a two-level handshake to ensure only one copy of the message is received (assured delivery).</p><p>We went ahead with QoS 1 as it achieved a middle-ground between QoS 0 and QoS 2 in terms of acknowledgment and lower latency. To handle the duplication issues that QoS 1 presents, we built a deduplication logic on the client side, based on a unique push notification identifier.</p><h4>Fallback Mechanism</h4><p>Next, we had to build a fallback mechanism when a client is offline(not connected to Courier) or not rolled out so we could send the push notification via FCM/APNs.</p><p>For maintaining a client’s online/offline status, we used VerneMQ <a href="https://courier-gojek.gitbook.io/vernemq/plugin-development/eventssidecarplugins">events</a> to create a user-liveness service, which is actually a Redis-based store, maintaining the online-offline status of a user. For a user logged in with multiple devices, this store maintains the status of each device.</p><p>Similarly, we created another Redis-based cache using VerneMQ <a href="https://courier-gojek.gitbook.io/vernemq/plugin-development/eventssidecarplugins">events</a>, for maintaining the subscribed topics of a client. This helps us decide whether the client is rolled out or not.</p><p>There can be cases when a user rolled out and also marked online in the user-liveness store but is not actually connected. In this case, we again fallback to FCM/APN when acknowledgment is not received within a particular interval.</p><h4>Topic Structure</h4><p>Courier uses MQTT as the underlying protocol which is based on Publish-Subscribe model. So we had to decide the structure of the topic to which clients would subscribe and Pusher would publish.</p><p>We created the topic using details like owner type and owner id to differentiate between users. We also included <a href="https://developer.android.com/reference/android/provider/Settings.Secure#ANDROID_ID">Android Device ID</a> to uniquely identify a particular device in case same user is logged in from multiple devices.</p><h3>New architecture</h3><p>The new flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djEi_GuvCrIcvGGdcCg-cw.png" /></figure><ol><li>All gojek services make an HTTP request to Pusher to send push notifications to the mobile apps.</li><li>Pusher makes a request to the token service to get details of all connected devices for a user.</li><li>Pusher checks the subscription cache if a user has subscribed to the push notification topic and then makes a request to user liveness service to get online/offline status for the user.</li><li>If the user is currently online and has subscribed to the push notification topic, Pusher publishes the push notification on the subscribed topic via Courier and enqueues a fallback job to Kafka. If the push notification status is not marked as delivered in PN Delivery cache within a specific interval, the fallback job sends the push notification via the old FCM/APNs flow.</li><li>When the user is either offline or has not subscribed to the push notification topic, Pusher directly sends the push notification via the old FCM/APNs flow.</li></ol><h3>Outcomes</h3><p>After the integration with Courier, we were able to see a significant increase in the reliability of push notifications.</p><p>For the Gojek customer app, we observed a delivery rate of <strong>95%+ for Courier flow while for FCM/APNs it was ~83%</strong>.</p><p>For the Gojek driver &amp; merchant apps, the delivery rate increased to <strong>99%+ for Courier flow while it was ~90% for FCM/APNs flow</strong>.</p><h3>Next steps</h3><p>With push notifications out of the way, stay tuned for the journey to integrate with Driver Bids at Gojek, the pulse of all we do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p>To read more stories from our vault, click <a href="https://www.gojek.io/blog/">here</a>.</p><p>Check out open job positions <a href="https://www.gojek.io/careers">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f690d5827b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/courier-reimagining-how-we-send-push-notifications-3f690d5827b9">Courier: Reimagining How We Send Push Notifications</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Courier Is Now Open-Source]]></title>
            <link>https://medium.com/gojekengineering/courier-is-now-open-source-454b7c752b0b?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/454b7c752b0b</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 06:18:11 GMT</pubDate>
            <atom:updated>2022-07-08T06:18:11.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here’s the new addition to our open source roster: Courier, a persisting connection that pushes content from our server to the app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8OVmYqZFte_0RtGvYxmHg.png" /></figure><p>Courier is the superhighway between mobile devices and our backend servers. It’s a persisting connection through which we’re able to push content from our server to the app. We’re excited to announce that we have open-sourced three Courier libraries for mobile and backend clients:</p><ul><li><a href="https://github.com/gojek/courier-android"><strong>courier-android</strong></a></li><li><a href="https://github.com/gojek/courier-iOS"><strong>courier-iOS</strong></a></li><li><a href="https://github.com/gojek/courier-go"><strong>courier-go</strong></a></li></ul><p>These client libraries can be used to create a long-running connection with an MQTT broker on Android, iOS, and Go applications.</p><blockquote>Courier is a scalable, low latency, and persistent network transmission mechanism for mobile&lt;&gt;server communication built over MQTT protocol.</blockquote><p><a href="https://gojek.github.io/courier/">Courier · Information Superhighway</a></p><h3>Features</h3><h4><strong>Quality of Service</strong></h4><p>All Courier libraries support three QoS levels for reliable message delivery: <strong>0</strong> (at most once), <strong>1</strong> (at least once) and <strong>2</strong> (exactly once).</p><h4>Automatic Reconnect</h4><p>All Courier libraries are able to reconnect automatically whenever there are network or other unexpected failures using a connection retry policy.</p><h4>Flexible Encoder/Decoder support</h4><p>All Courier libraries provide support for converting MQTT message payload to or from any custom message type.</p><h4>Clean &amp; easy to understand APIs</h4><p>All Courier libraries provide clean APIs for <strong>connect</strong>/<strong>disconnect</strong>, <strong>subscribe</strong>/<strong>unsubscribe</strong> and <strong>publish</strong>/<strong>receive</strong> functionalities. The APIs are simple and easy to understand.</p><h4>Observability</h4><p>Courier libraries also provide events for tracking end-to-end message delivery and connection lifecycle.</p><h4>Documentation</h4><p>All Courier libraries are well-documented with examples. Also, these libraries have their own individual documentations hosted on github pages.<br><strong>courier-android</strong> : <a href="https://gojek.github.io/courier-android/">https://gojek.github.io/courier-android</a><br><strong>courier-iOS</strong> : <a href="https://gojek.github.io/courier-iOS/">https://gojek.github.io/courier-iOS</a><br><strong>courier-go</strong> : <a href="https://gojek.github.io/courier-go/">https://gojek.github.io/courier-go</a></p><p>You can read more about courier <a href="https://gojek.github.io/courier/">here</a>. Also, you can find the <a href="https://gojek.github.io/courier/docs/Introduction">end-to-end chat example</a> created using these courier libraries.</p><p>Other library-specific features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f4LP6z_aWlDuiYERk_lVg.png" /></figure><p>We have also covered <a href="https://medium.com/gojekengineering/courier-library-for-gojeks-information-superhighway-368dc5f052fa">Android</a> &amp; <a href="https://medium.com/gojekengineering/courier-a-realtime-lightweight-messaging-highway-in-ios-with-mqtt-1dc7dffa951a">iOS</a> libraries in detail in our blogs.</p><p>Oh, it’s a five-part series, so your tech reading for the weekend is sorted. 🖖</p><p><a href="https://bit.ly/3jCOARH">Introducing Courier - The Information Superhighway Between Mobile &amp; Server - 5 min read</a></p><h4>How to reach out?</h4><p>You can join our <a href="https://discord.gg/C823qK4AK7">discord server</a> to connect with the team behind this amazing project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p>Find more stories from our vault, <a href="https://www.gojek.io/blog">here</a>.<br>Also, we’re hiring! Check out open job positions by clicking below:</p><figure><a href="https://bit.ly/gojekjobsblogs2022"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*c2_eIvR2WDUWnP6YmzcGpQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454b7c752b0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/courier-is-now-open-source-454b7c752b0b">Courier Is Now Open-Source</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaptive Heartbeats For Our Information Superhighway]]></title>
            <link>https://medium.com/gojekengineering/adaptive-heartbeats-for-our-information-superhighway-26459bf85d62?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/26459bf85d62</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[adaptive-keepalive]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[keep-alive]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Tue, 16 Nov 2021 05:30:37 GMT</pubDate>
            <atom:updated>2021-11-16T05:30:37.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>How the ‘Adaptive Keepalive’ feature in our Courier library finds the most optimal Keepalive interval for a client on a particular network.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehXX1VCVTiztlAqEnVJBHw.jpeg" /></figure><p>In our previous posts from the Courier series, we had discussed about the Courier library for mobile clients. We had also briefly discussed the Adaptive Keepalive feature, used for optimising the number of ping requests (or Keepalive packets) sent over the network.</p><p>In this post, we’ll talk about the Adaptive Keepalive feature.</p><h4>Background</h4><p>When a long-running connection between a client and a server is idle for a long time, it may get torn down due to <strong>TCP binding timeout</strong>. In order to keep the connection alive, the client device needs to send keep-alive packets(or ping requests) through the connection when it is otherwise idle. The interval at which these packets are sent is the <strong>Keepalive Interval.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*VeQon9qg9gigjFOp6qg71Q.png" /></figure><p>The Courier library uses <strong>AlarmPingSender </strong>for sending ping requests, which schedules alarms to wake up the device when it needs to send a <strong>PING REQUEST</strong> to the MQTT broker.</p><p>We can see that <strong>the number of alarms triggered is directly proportional to the number of ping requests sent.</strong> Also, <strong>each time a keep-alive packet is sent, there is the cost of bringing the radio to a high power state, if the device was otherwise idle.</strong> Both of these be reduced by minimising the number of ping requests sent.</p><h3>Adaptive Keepalive</h3><p>Adaptive Keepalive is a feature in the Courier library which tries to find the most optimal Keepalive interval for a client on a particular network. This helps in optimising the number of ping requests sent over the network and keeping the connection alive.</p><blockquote>Optimal Keepalive interval is the farthest time possible within the TCP binding timeout, which means that an idle connection cannot be kept alive beyond this interval.</blockquote><p>There are multiple possible approaches for finding the optimal Keepalive interval like <strong>Binary Search, Exponential Search, Composite Search</strong>,<strong> </strong>and <strong>Linear Search</strong>.</p><h4>Approaches</h4><p>All approaches use an iterative probing that repeatedly send keep-alive packets at progressively longer intervals, until the optimal keep-alive interval is found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdd7lw5JqRPoNvYWwaL0kA.png" /></figure><p>This flowchart explains how optimal keep-alive interval is found using probing. This process is continued till <strong>high &gt; low</strong>.</p><p>All the approaches are evaluated on basis of following parameters:</p><ul><li><strong>Probe Count:</strong> Number of probes performed in finding the optimal keep-alive interval.</li><li><strong>Convergence Time:</strong> Total time taken to find the optimal keep-alive interval.</li></ul><h4><strong>Binary Search</strong></h4><p>In this approach, <strong>alpha</strong> is chosen as <strong>(low+high)/2</strong> i.e., at each iteration, the mid-point of the search space is chosen as the next KA interval to be tested. After the test is completed, the search space gets halved. <br>If the test was successful, then we search the second half of the initial search space to see if a better interval can be obtained. If, on the other hand, the test failed, then we continue searching in the first half of the initial search space. And this process is repeated.</p><h4><strong>Exponential Search</strong></h4><p>In this approach, the difference between successive tested intervals follows geometric progression with a ratio of 2. So, the first few test intervals are 2, 4, 8, 16, 32 minutes and so on. If the next interval to be tested goes beyond <em>high</em>, then there is no need to test that interval. Instead, <em>low</em> is increased to the last successfully tested interval; and the progression of the interval differences is restarted at 1. On the other hand, if the next tested interval overshoots the binding timeout, then the connection is lost. In this case, in addition to the updates mentioned above, the <em>high</em> is reduced to 1 minute less than the failed test interval. This process is repeated until the optimal KA interval is reached.</p><h4><strong>Composite Search</strong></h4><p>Composite search is a combination of binary and exponential searches. Initially, it acts like the exponential search. The difference between successive tested intervals follows geometric progression with ratio of 2. <br>When a tested interval overshoots the actual binding timeout, the connection will get terminated. At that point, <em>low</em> is increased to the last successfully tested interval; and <em>high</em> is reduced to 1 minute less than the failed test interval. Subsequently, binary search is performed in the new search range.</p><h4><strong>Linear Search</strong></h4><p>In linear search, the difference between successive tested intervals follows an arithmetic progression. So, the first few test intervals are 4, 8, 12, 16, 20 minutes and so on. If the next interval to be tested goes beyond <em>high</em>, then there is no need to test that interval. Instead, <em>low</em> is increased to the last successfully tested interval; and the progression of the interval differences is decreased by half. On the other hand, if the next tested interval overshoots the binding timeout, then the connection is lost. In this case, in addition to the updates mentioned above, the <em>high</em> is reduced to 1 minute less than the failed test interval. This process is repeated until the optimal KA interval is reached.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO86EP5uO145xWYqx-K_zg.png" /><figcaption>Comparison of multiple approaches</figcaption></figure><ul><li>In the above experiment, all approaches are evaluated for a lower bound of 4 minutes and upper bound of 120 minutes.</li><li>For low optimal Keepalive values, exponential search and composite search takes least amount of time and minimum number of keepalive packets are sent.</li><li>For high optimal Keepalive values, binary search performs the best with minimum time and Keepalive packets being sent.</li><li>Linear search also works well when the difference between lower and upper bounds is not very wide and the value of d is chosen wisely. Also, its the most simple approach in terms of implementation.</li></ul><h4>Network Change Behaviour</h4><p>TCP binding timeout can vary significantly for different networks. Therefore it is important to calculate the optimal keep-alive interval for every network change.</p><p>Also, finding the optimal keep-alive interval for a particular network can be a long running process. So the clients should persist the optimal keep-alive interval found for a particular network.</p><h4>Impact of Keepalive packet failure</h4><p>So far, when a Keepalive message fails over the connection, we have assumed that the middle-box has dropped the connection due to too long an idleness. However, a packet could also be dropped for some transient issues in the network.</p><p>In case of mobile devices, the sender can also go back in sleep mode after sending the keep-alive packet which would result into ping failure.</p><p>The sender has no way to differentiate between the different causes of failure. This can be solved by sending keep-alive packet multiple times whenever a failure happens. If it fails every time, it can be safely considered a valid case.</p><h3>References</h3><p><a href="https://www.researchgate.net/publication/321845435_Using_Adaptive_Heartbeat_Rate_on_Long-Lived_TCP_Connections">Using Adaptive Heartbeat Rate on Long-Lived TCP Connections</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p>Find more stories from our vault, <a href="https://www.gojek.io/blog">here</a>.<br>Also, we’re hiring! Check out open job positions by clicking below:</p><figure><a href="https://bit.ly/gojekjobsblogs2021"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*c2_eIvR2WDUWnP6YmzcGpQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26459bf85d62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/adaptive-heartbeats-for-our-information-superhighway-26459bf85d62">Adaptive Heartbeats For Our Information Superhighway</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Courier Library For Gojek’s Information Superhighway]]></title>
            <link>https://medium.com/gojekengineering/courier-library-for-gojeks-information-superhighway-368dc5f052fa?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/368dc5f052fa</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[gojek]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 05:12:03 GMT</pubDate>
            <atom:updated>2021-10-01T05:12:03.356Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is part-3 of how we built Courier, the information superhighway between mobile devices and our backend servers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqJaIYtL6rex_Z5tR2vWlA.png" /></figure><p>In <a href="https://medium.com/gojekengineering/introducing-courier-the-information-superhighway-between-mobile-server-87a5973287a7">Part-1</a> and <a href="https://medium.com/gojekengineering/the-quest-for-a-message-broker-for-our-courier-c05c5238372f">Part-2</a> of the Courier series, we spoke about our rationale behind building Courier and the quest for a message broker for Courier. Here’s a quick recap:</p><ul><li>We had decided to replace HTTP polling with a long-running persistent connection for sending order updates to our merchants.</li><li>This was done due to multiple issues with polling like high data &amp; battery consumption, non-deterministic behavior, and high infra usage.</li><li>Multiple protocols were explored for long-running connection like <a href="https://grpc.io/about/">gRPC</a>, <a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a>, <a href="https://mqtt.org/">MQTT</a>. The finalized protocol was MQTT over TCP.</li><li>Few major reasons for choosing MQTT were small network footprint, multiple QoS(Quality of Service) levels, and built-in acknowledgment.</li><li>The MQTT broker chosen was <a href="https://vernemq.com/">VerneMQ</a> which is an open-source, performant, and highly available message broker implementation.</li></ul><p>Read more here:</p><ul><li><a href="https://medium.com/gojekengineering/introducing-courier-the-information-superhighway-between-mobile-server-87a5973287a7">Introducing Courier — The Information Superhighway Between Mobile &amp; Server</a></li><li><a href="https://medium.com/gojekengineering/the-quest-for-a-message-broker-for-our-courier-c05c5238372f">The Quest For A Message Broker For Our ‘Courier’</a></li></ul><blockquote>Courier is our in-house solution to provide a realtime, lightweight, and high efficient messaging highway between mobile apps and server using MQTT.</blockquote><p>When we had started with the design of Courier library for our merchant app, we had a few questions in mind:</p><ul><li>Which library should we use for MQTT client implementation? Or should we create our own library?</li><li>How to solve the Android platform-specific issues?</li></ul><p>Let me answer each question individually.</p><h4>Should we create our own library or use an existing one?</h4><p>Actually, we did a combination of both. We used an existing library for MQTT protocol implementation and created our own library on top of it.</p><p>The library which we used for MQTT implementation is <a href="https://github.com/eclipse/paho.mqtt.java"><strong>Paho</strong></a>. It is a very popular open-source library written in Java and maintained by <strong>Eclipse</strong>.</p><blockquote>According to the documentation, Paho Java client is an MQTT client library written in Java for developing applications that run on the JVM or other Java compatible platforms such as Android</blockquote><p>Now, the question comes — what was the reason for creating a new library on top of Paho? So, there were multiple reasons for doing this.</p><p>Paho is a simple MQTT protocol implementation, providing two types of APIs: blocking and non-blocking. It handles all the protocol-specific logic like creating an MQTT connection, subscribing/unsubscribing a topic, publishing &amp; receiving messages, and disconnecting an existing connection. But it is not a full-fledged library needed for maintaining a long-running persistent connection.</p><p>Now let’s have a look at the features which the Courier Android library provides.</p><h3>Courier library features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DYVcVo7C1XsraFoxCL2_w.png" /></figure><h4>Clean API</h4><p>Courier library provides a <a href="https://github.com/square/retrofit">Retrofit</a>-inspired interface for <strong>Send</strong>, <strong>Receive</strong>, <strong>Subscribe</strong> and <strong>Unsubscribe</strong> operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff11b641619cd72b6f78332758631be/href">https://medium.com/media/aff11b641619cd72b6f78332758631be/href</a></iframe><p>For <strong>connect</strong> and <strong>disconnect</strong> API, Courier library provides a separate interface — MqttClient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71bd6352441c09949ae66eaa33e6f67d/href">https://medium.com/media/71bd6352441c09949ae66eaa33e6f67d/href</a></iframe><h4>Message adapters and stream adapters support</h4><p>Similar to <strong>Retrofit</strong>, the Courier library provides the support of adding custom message and stream adapters. <br>By default, the library provides support of <a href="https://github.com/google/gson"><strong>Gson</strong></a>, <a href="https://github.com/square/moshi"><strong>Moshi</strong></a> &amp; <a href="https://github.com/protocolbuffers/protobuf"><strong>Protobuf</strong></a> message adapters and <a href="https://github.com/ReactiveX/RxJava"><strong>RxJava2</strong></a> &amp; <a href="https://kotlinlang.org/docs/flow.html#flows"><strong>Coroutines(Flow)</strong></a> stream adapters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89680c1165addfe818825eb7b877ec4a/href">https://medium.com/media/89680c1165addfe818825eb7b877ec4a/href</a></iframe><h4>Automatic Reconnect</h4><p>This is one of the most important features of the Courier library. Whenever the MQTT connection is disconnected due to non-user-initiated actions like network loss or socket read timeout, the library tries to reconnect automatically. The exact retry logic is decided by retry policies, which we will discuss soon.</p><h4>Subscription store &amp; Automatic Resubscribe</h4><p>Subscription store keeps track of the subscribed topics and pending unsubscribes.</p><p>Subscribed topics are used for automatic resubscription when the client gets reconnected on <strong>non-persistent connections(cleansession=true).</strong></p><p>Pending unsubscribe topics are maintained for avoiding stale subscriptions on the MQTT broker for <strong>persistent connections(cleansession=false)</strong>.</p><h4>Retry &amp; Fallback policies</h4><p>There are different types of policies provided by Courier library — <strong>connect retry policy, subscription policy, host fallback policy</strong>. These policies decide what action should be performed when a failure occurs and what should be the delay in case of retry.</p><p><strong>Connect retry policy</strong> decides whether the connection should be retried again when a connection failure happens and the next retry time.</p><p><strong>Subscription retry policy</strong> decides whether the subscription should be retried again when a subscription request fails and the next retry time.</p><p><strong>Host fallback policy</strong> decides the next host be retried when multiple hosts are available and the connection fails on one of the hosts.</p><h4>AlarmPingSender</h4><p>Paho provides the support of PingSender which can be used for sending <strong>PING REQUESTS</strong> over the MQTT connection in order to keep the connection alive as long as possible.</p><p>Courier library makes use of two implementations of PingSender: <strong>AlarmPingSender </strong>and <strong>TimerPingSender.</strong></p><p>Courier library uses the <strong>AlarmPingSender</strong> implementation which provides support of <a href="https://developer.android.com/reference/android/app/AlarmManager#ELAPSED_REALTIME_WAKEUP"><strong>ELAPSED_REALTIME_WAKEUP</strong></a>,<strong> </strong><a href="https://developer.android.com/reference/android/app/AlarmManager#RTC_WAKEUP"><strong>RTC_WAKEUP</strong></a>,<strong> </strong><a href="https://developer.android.com/reference/android/app/AlarmManager#ELAPSED_REALTIME"><strong>ELAPSED_REALTIME</strong></a>,<strong> </strong>and<strong> </strong><a href="https://developer.android.com/reference/android/app/AlarmManager#RTC"><strong>RTC</strong></a><em> </em>alarms to schedule pings. <br>The library uses <strong>RTC_WAKEUP,</strong> which works in doze mode and other power-saving modes(with some restrictions) as well. This helps in keeping the connection alive when the app is in the background. This is also discussed in detail later.</p><p><a href="https://github.com/eclipse/paho.mqtt.java/blob/master/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/TimerPingSender.java"><strong>TimerPingSender</strong></a><strong> </strong>is used for cases where the connection is not needed to be alive in the background. It uses <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html"><strong>Timer</strong></a> for scheduling pings.</p><h4>Adaptive Keepalive</h4><p>Adaptive keepalive is a feature in the Courier library which tries to find the most optimal keepalive interval for a client on a particular network. This helps in optimising the number of ping requests sent over the network and keeping the connection alive. This will be discussed in greater detail, in a separate blog.</p><h4>Backpressure Handling</h4><p>Courier library handles the backpressure using internal persistence by storing all the received messages first and then delivering them to the library’s client.</p><blockquote>Backpressure is a situation where producer produces at a pace faster than the pace at which the consumer is consuming.</blockquote><h4>Database Persistence</h4><p>Paho provides support for persistence but it provides only file-based persistence which is not very efficient for mobile devices. Courier library provides an SQLite database implementation of the MqttClientPersistence interface provided by Paho.</p><h4>Event Provider</h4><p>Courier library provides many events out of the library which can be used for multiple purposes like taking an action when a particular event happens or just adding analytics for tracking the system metrics.<br>For example, the library provides connect events, subscribe events, ping events, message send &amp; receive events, and many more.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f97d00ecb9348a35571831bb0376b69e/href">https://medium.com/media/f97d00ecb9348a35571831bb0376b69e/href</a></iframe><h4>MQTT Chuck</h4><p>MQTT Chuck is similar to <a href="https://github.com/jgilfelt/chuck">HTTP Chuck</a>, used for inspecting the HTTP calls on an android application. MQTT chuck inspects all the outgoing or incoming packets for an underlying MQTT connection.</p><p>Similar to HTTP Chuck, it uses an interceptor to intercept all the packets, persisting them and providing a UI for accessing all the MQTT packets sent or received. It also provides multiple other features like search, share, and clear data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OG3kRTqr1i38F5MNP5BB2A.png" /></figure><h4>Authentication</h4><p>Clients need to be authenticated before making an MQTT connection in order to permit only authenticated users to access the MQTT broker. MQTT protocol uses a combination of username and password for authentication.</p><p>Courier library provides a mechanism to fetch authentication details like JWT token and broker address by making an API call, which is further used for MQTT authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHo9hMkiuJYh-SRk1I9mOg.png" /></figure><p>That’s all about the features of our Courier library. Let’s now discuss the platform-specific challenges we faced.</p><h3>Android platform-specific challenges</h3><p>Android OS has become very conservative about the battery usage by applications, especially when the app is in the background. Applications also have a high chance of getting killed by OS, if they are running in the background for a long time without any component visible to the user.</p><p>Also, there are multiple <a href="https://developer.android.com/training/monitoring-device-state/doze-standby">power-saving modes</a> on Android like <strong>Sleep mode</strong>, <strong>Doze mode</strong>, and <strong>App Standby</strong> mode. The device enters these modes when it is not charging and the device/app is not used for a long time.</p><p>A long-running connection needs to keep running in both foreground and background. So it becomes important to consider the above cases at the time of implementation.</p><p>Courier library handles this by using <strong>AlarmPingSender</strong> which schedules <strong>RTC_WAKEUP</strong> alarms using AlarmManager’s setExactAndAllowWhileIdle() API for sending ping requests in order to keep the connection alive.</p><p>Due to the restrictions in doze mode, neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire alarms more than once per 9 minutes, per app. So we introduced Adaptive Keepalive, which minimises the number of alarms scheduled by finding the most optimal keepalive time on a particular network.</p><h3>What’s Next?</h3><p>We are planning to expand Courier for multiple use-cases like Chat and Realtime Event Tracking. This will also help us to achieve our long-term goal of having a single long-running connection on the Gojek app.</p><p>We also have future plans of making the Courier library for Android open-source. Follow <a href="https://github.com/orgs/gojek/repositories">here</a> for the open-source projects by Gojek.</p><p><a href="https://github.com/gojek">Gojek</a></p><p>Stay tuned! In the next blog, we’ll talk about the iOS Courier library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p>Find more stories from our vault, <a href="https://www.gojek.io/blog">here</a>.<br>Also, we’re hiring! Check out open job positions by clicking below:</p><figure><a href="https://bit.ly/gojekjobsblogs2021"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*c2_eIvR2WDUWnP6YmzcGpQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=368dc5f052fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/courier-library-for-gojeks-information-superhighway-368dc5f052fa">Courier Library For Gojek’s Information Superhighway</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android ViewModels : Under the hood]]></title>
            <link>https://medium.com/mindorks/android-viewmodels-under-the-hood-ddc679d77dd5?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc679d77dd5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 02:58:24 GMT</pubDate>
            <atom:updated>2020-07-14T02:58:24.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFk0dnBc4PGDEsh_SYUQIw.jpeg" /></figure><h3>Android ViewModels: Under the hood</h3><p>In this article, we are going to discuss the internals of ViewModel which is a part of Android Architecture Components. We will first briefly discuss the usages of ViewModel in Android and then we will go in detail about how ViewModel actually works and how it retains itself on configuration changes.</p><p><strong>Originally published at </strong><a href="https://blog.mindorks.com/android-viewmodels-under-the-hood"><strong>blog.mindorks.com</strong></a></p><p>According to the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">documentation</a>, the ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.</p><p>The ViewModel class also helps in implementing <strong>MVVM(Model-View-ViewModel)</strong> design pattern which is also the recommended Android app architecture for Android applications by Google.</p><p>Also, there are other various advantages of using ViewModel class provided by Android framework like:</p><ul><li><strong>Handle configuration changes:</strong> ViewModel objects are automatically retained whenever activity is recreated due to configuration changes.</li><li><strong>Lifecycle Awareness:</strong> ViewModel objects are also lifecycle-aware. They are automatically cleared when the Lifecycle they are observing gets permanently destroyed.</li><li><strong>Data Sharing:</strong> Data can be easily shared between fragments in an activity using ViewModels.</li><li><strong>Avoid memory leaks:</strong> Viemodels also help in avoiding memory leaks as they do not keep an instance of activity/fragment.</li><li><strong>Kotlin-Coroutines support:</strong> ViewModel includes support for <a href="https://blog.mindorks.com/mastering-kotlin-coroutines-in-android-step-by-step-guide">Kotlin-Coroutines</a>. So, they can be easily integrated for any asynchronous processing.</li></ul><h4>How ViewModel work internally?</h4><p><a href="https://github.com/deepanshu42/viewmodel-sample">Link to the sample project</a></p><p>This is the sample project we are going to use for explaining how the viewmodel retains itself on configuration changes.</p><p>This is a very simple application with a single activity named MainActivity which shows a counter. The counter value is our view state kept inside the CounterViewModel using a LiveData object. The activity also shows the hashcode of the current activity instance.</p><p>On any configuration change, the current activity instance is destroyed and a new instance of the activity is created which makes the hashcode to change. But the counter value is retained as we are keeping it inside our ViewModel and the viewmodels are not destroyed if the activity is getting recreated due to configuration changes.</p><p>The first thought around how viewmodels are retained might be that they are stored somewhere at the global(application) level and that’s why they are not destroyed when the activity is recreated. But this assumption is wrong. The viewmodels are stored inside the activity (or FragmentManager in case of fragments).</p><p>So let’s discuss how this magic happens and how our viewmodel instance is retained even if the activity is recreated.</p><pre>viewModel = ViewModelProvider(<strong>this</strong>, ViewModelFactory()).get(CounterViewModel::<strong>class</strong>.<strong>java</strong>)</pre><p>This is the code to get a viewmodel instance in an activity. As we can see, we are getting an instance of ViewModelProvider by passing two arguments, our activity instance and an instance of ViewModelFactory. Then, we are using this ViewModelProvider instance to get our CounterViewModel object.</p><blockquote>Note: In the above example, passing <strong>ViewModelFactory</strong> is redundant as our <strong>CounterViewModel</strong> does not have a parameterized constructor. In case we do not pass <strong>ViewModelFactory,</strong> ViewModelProvider uses a default view model factory.</blockquote><p>So the creation of viewmodel involves 2 steps:</p><ol><li>Creation of ViewModelProvider</li><li>Getting the instance of Viewmodel from ViewModelProvider</li></ol><h4>Creation of ViewModelProvider</h4><pre><strong>public</strong> <strong>ViewModelProvider</strong>(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {<br>    <strong>this</strong>(owner.getViewModelStore(), factory);<br>}</pre><p>The constructor of ViewModelProvider takes two parameters, ViewModelStoreOwner and Factory. In our example, the activity is the ViewModelStoreOwner and we are passing our own custom factory. ViewModelStoreOwner is a simple interface with a single method named getViewModelStore()</p><pre><strong>public</strong> <strong>interface</strong> <strong>ViewModelStoreOwner</strong> {<br>    <strong>@NonNull</strong><br>    ViewModelStore <strong>getViewModelStore</strong>();<br>}</pre><p>In the constructor, we are simply getting the ViewModelStore from ViewModelStoreOwner and passing it to the other constructor where they are just assigned to the respective class members.</p><pre><strong>public</strong> <strong>ViewModelProvider</strong>(@NonNull ViewModelStore store, @NonNull Factory factory) {<br>    mFactory = factory;<br>    mViewModelStore = store;<br>}</pre><p>So now we know that our activity is the ViewModelStoreOwner and its the responsibility of our activity to provide the ViewModelStore.</p><h4>Getting the ViewModel from ViewModelProvider</h4><pre><strong>public</strong> &lt;T extends ViewModel&gt; T <strong>get</strong>(@NonNull Class&lt;T&gt; modelClass) {<br>    String canonicalName = modelClass.getCanonicalName();<br>    <strong>if</strong> (canonicalName == <strong>null</strong>) {<br>        <strong>throw</strong> <strong>new</strong> IllegalArgumentException(&quot;Local and anonymous classes can not be ViewModels&quot;);<br>    }<br>    <strong>return</strong> get(DEFAULT_KEY + &quot;:&quot; + canonicalName, modelClass);<br>}</pre><p>When we invoke get() method on our ViewModelProvider, it gets the <strong>canonical name</strong> of the view model class and creates a key by appending the <strong>canonical name</strong> to a <strong><em>DEFAULT_KEY</em></strong>.</p><pre><strong>public</strong> &lt;T extends ViewModel&gt; T <strong>get</strong>(@NonNull String key, @NonNull Class&lt;T&gt; modelClass) {<br>    ViewModel viewModel = mViewModelStore.get(key);</pre><pre>    <strong>if</strong> (modelClass.isInstance(viewModel)) {<br>        <strong>if</strong> (mFactory <strong>instanceof</strong> OnRequeryFactory) {<br>            ((OnRequeryFactory) mFactory).onRequery(viewModel);<br>        }<br>        <strong>return</strong> (T) viewModel;<br>    } <strong>else</strong> {<br>        <em>//noinspection StatementWithEmptyBody</em><br>        <strong>if</strong> (viewModel != <strong>null</strong>) {<br>            <em>// TODO: log a warning.</em><br>        }<br>    }<br>    <strong>if</strong> (mFactory <strong>instanceof</strong> KeyedFactory) {<br>        viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);<br>    } <strong>else</strong> {<br>        viewModel = (mFactory).create(modelClass);<br>    }<br>    mViewModelStore.put(key, viewModel);<br>    <strong>return</strong> (T) viewModel;<br>}</pre><p>After creating the key from the model class, it checks the ViewModelStore (which is provided by our activity) whether a viewmodel instance for the given key is already present or not. If the viewmodel is already present, it simply returns the viewmodel instance present in ViewModelStore and if it’s not present, the ViewModelProvider uses the Factory instance to create a new viewmodel object and also stores it in ViewModelStore.</p><p>Now we know that our activity is responsible for storing the ViewModel instances. But it’s still a mystery that how these ViewModel instances are retained even when the activity instance is recreated on configuration change.</p><h4>How ViewModel retain itself?</h4><p>As we saw earlier when we created ViewModelProvider we were passing an instance of ViewModelStoreOwner i.e., our activity instance.</p><pre><strong>public</strong> <strong>class</strong> <strong>ComponentActivity</strong> <strong>extends</strong> <strong>androidx</strong>.<strong>core</strong>.<strong>app</strong>.<strong>ComponentActivity</strong> <strong>implements</strong><br>        <strong>LifecycleOwner</strong>,<br>        <strong>ViewModelStoreOwner</strong>,<br>        <strong>SavedStateRegistryOwner</strong>,<br>        <strong>OnBackPressedDispatcherOwner</strong></pre><p>Our activity implements the ViewModelStoreOwner the interface which has a single method named getViewModelStore()</p><pre><strong>public</strong> <strong>interface</strong> <strong>ViewModelStoreOwner</strong> {<br>    <strong>@NonNull</strong><br>    ViewModelStore <strong>getViewModelStore</strong>();<br>}</pre><p>Now let’s have a look at the implementation of this method.</p><pre><strong>@NonNull</strong><br><strong>@Override</strong><br><strong>public</strong> ViewModelStore <strong>getViewModelStore</strong>() {<br>    <strong>if</strong> (getApplication() == <strong>null</strong>) {<br>        <strong>throw</strong> <strong>new</strong> IllegalStateException(&quot;Your activity is not yet attached to the &quot;<br>                + &quot;Application instance. You can&#39;t request ViewModel before onCreate call.&quot;);<br>    }    <em>//This is true when invoked for the first time</em><br>    <strong>if</strong> (mViewModelStore == <strong>null</strong>) {<br>        NonConfigurationInstances nc =<br>                (NonConfigurationInstances) getLastNonConfigurationInstance();<br>        <strong>if</strong> (nc != <strong>null</strong>) {<br>            <em>// Restore the ViewModelStore from NonConfigurationInstances</em><br>            mViewModelStore = nc.viewModelStore;<br>        }<br>        <strong>if</strong> (mViewModelStore == <strong>null</strong>) {<br>            mViewModelStore = <strong>new</strong> ViewModelStore();<br>        }<br>    }<br>    <strong>return</strong> mViewModelStore;<br>}</pre><p>Here we can see that getViewModelStore() returns the <strong>mViewModelStore.</strong> When our activity is recreated due to any configuration change, nc(NonConfigurationInstances) contains the previous instance of ViewModelStore. nc(NonConfigurationInstances) is null when our activity is created for the first time and a new ViewModelStore is created in this case.</p><pre><em>//ComponentActivity.java</em><br><strong>static</strong> <strong>final</strong> <strong>class</strong> <strong>NonConfigurationInstances</strong> {<br>    Object custom;<br>    ViewModelStore viewModelStore;<br>}<em>//Activity.java</em><br><strong>static</strong> <strong>final</strong> <strong>class</strong> <strong>NonConfigurationInstances</strong> {<br>    Object activity;  <em>//NonConfigurationInstances(ComponentActivity)</em><br>    HashMap&lt;String, Object&gt; children;<br>    FragmentManagerNonConfig fragments;<br>    ArrayMap&lt;String, LoaderManager&gt; loaders;<br>    VoiceInteractor voiceInteractor;<br>}</pre><p>NonConfigurationInstances(Activity.java) is the object which is retained by the Android system even when the activity gets recreated. It has a member named activity which is an instance of NonConfigurationInstances(ComponentActivity.java). This instance contains ViewModelStore.</p><blockquote>Note: ViewModels are not retained directly. Instead, ViewModelStore is retained on configuration changes which internally maintains a map of viewmodels.</blockquote><p>Let’s deep dive more into this.</p><pre><em>//Activity.java</em><br><strong>public</strong> Object <strong>getLastNonConfigurationInstance</strong>() {<br>    <strong>return</strong> mLastNonConfigurationInstances != <strong>null</strong><br>            ? mLastNonConfigurationInstances.activity : <strong>null</strong>;<br>}<em>//ComponentActivity.java</em><br><strong>public</strong> <strong>final</strong> Object <strong>onRetainNonConfigurationInstance</strong>() {<br>    Object custom = onRetainCustomNonConfigurationInstance();</pre><pre>    ViewModelStore viewModelStore = mViewModelStore;<br>    <strong>if</strong> (viewModelStore == <strong>null</strong>) {<br>        <em>// No one called getViewModelStore(), so see if there was an existing</em><br>        <em>// ViewModelStore from our last NonConfigurationInstance</em><br>        NonConfigurationInstances nc =<br>                (NonConfigurationInstances) getLastNonConfigurationInstance();<br>        <strong>if</strong> (nc != <strong>null</strong>) {<br>            viewModelStore = nc.viewModelStore;<br>        }<br>    }</pre><pre>    <strong>if</strong> (viewModelStore == <strong>null</strong> &amp;&amp; custom == <strong>null</strong>) {<br>        <strong>return</strong> <strong>null</strong>;<br>    }</pre><pre>    NonConfigurationInstances nci = <strong>new</strong> NonConfigurationInstances();<br>    nci.custom = custom;<br>    nci.viewModelStore = viewModelStore;<br>    <strong>return</strong> nci;<br>}</pre><p>Whenever our activity is getting recreated due to any configuration change, onRetainNonConfigurationInstance() gets invoked which returns the NonConfigurationInstances(ComponentActivity.java) instance. This object is retained by the Android system so that it can be delivered to the next activity instance on recreation.</p><p>Similarly, we can also retain our own custom objects by implementing the onRetainCustomNonConfigurationInstance().</p><p>After the recreation of our activity, NonConfigurationInstances(Activity.java) is received in the attach() method of the Activity class.</p><pre><strong>final</strong> <strong>void</strong> <strong>attach</strong>(Context context, ActivityThread aThread,<br>        Instrumentation instr, IBinder token, <strong>int</strong> ident,<br>        Application application, Intent intent, ActivityInfo info,<br>        CharSequence title, Activity parent, String id,<br>        NonConfigurationInstances lastNonConfigurationInstances,<br>        Configuration config, String referrer, IVoiceInteractor voiceInteractor,<br>        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken)</pre><p>This is how the viewmodels are retained on configuration changes.</p><p>You can also connect with me on <a href="https://www.linkedin.com/in/deepanshu42/">LinkedIn</a>, <a href="https://twitter.com/deep1743">Twitter</a>, <a href="https://www.facebook.com/deepanshu42">Facebook</a>, and <a href="https://github.com/deepanshu42">Github</a>.</p><p>Thank You!!!</p><h4>References</h4><p><a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel overview | App architecture | Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc679d77dd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/android-viewmodels-under-the-hood-ddc679d77dd5">Android ViewModels : Under the hood</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</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 Room Persistent Library in Android]]></title>
            <link>https://medium.com/mindorks/introduction-to-room-persistent-library-in-android-5d7c340d0fbc?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d7c340d0fbc</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Sat, 23 May 2020 12:07:50 GMT</pubDate>
            <atom:updated>2020-05-23T12:07:50.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r_S9rURg_tOrPPm0.png" /></figure><p>Welcome to the <strong>Advanced Room series</strong> which covers all the details about <strong>Room Persistent Library</strong>. In this series, we will start with the basics of Room, then we will learn how to use it. We will learn about the various components of Room in detail and we will also learn how to use Room with <strong>LiveData</strong> and other third-party libraries like <strong>RxJava</strong> and <strong>Kotlin coroutines</strong>. Here is the list of the blogs in this series:</p><ul><li><strong>Introduction to Room Persistent Library in Android [You are here]</strong></li><li><a href="https://medium.com/@deepanshu42/data-access-objects-dao-in-room-3d108d6b4b54">Data Access Objects — DAO in Room</a></li><li><a href="https://medium.com/@deepanshu42/entity-relationship-in-room-b61cfcbf395">Entity Relationship in Room</a></li><li><a href="https://medium.com/@deepanshu42/how-does-room-work-internally-c17572b03bed">How does Room work internally?</a></li><li><a href="https://medium.com/@deepanshu42/room-database-migrations-35a57bdd0ce6">Room Database Migrations</a></li><li><a href="https://medium.com/@deepanshu42/using-room-with-live-data-and-other-third-party-libraries-18000fe017b2">Using Room with LiveData and other third-party libraries</a></li></ul><h3>Room Introduction</h3><p>This part covers the basics of Room persistence library. After reading this, you can start using Room in your android applications.</p><p>Room is an Android persistence library that is part of Google’s <a href="https://developer.android.com/jetpack">Android Jetpack</a> project. According to the documentation, Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.</p><p>Apps that handle significant amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data. That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.</p><h3>Adding Room in your project</h3><p>Add the following in your module’s(app) build.gradle file:</p><pre>dependencies {<br>  implementation &quot;androidx.room:room-runtime:2.2.5&quot;<br>  kapt &quot;androidx.room:room-compiler:2.2.5&quot;<br>}</pre><h3>Advantages of using Room</h3><p>There are multiple advantages of using Room as compared to other alternative solutions like SQLiteOpenHelper:</p><ul><li>Compile-time verification of queries.</li><li>Reduces boilerplate code.</li><li>Easy to understand and use.</li><li>Easy integration with RxJava, LiveData, and Kotlin Coroutines.</li></ul><h3>Components of Room</h3><p>There are 3 major components in Room:</p><ul><li><strong>Database: </strong>Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.</li><li><strong>Entity: </strong>Represents a table within the database.</li><li><strong>DAO: </strong>Contains the methods used for accessing the database.</li></ul><p>Your application uses the <strong>Room database</strong> to get the <strong>data access objects</strong>, or <strong>DAOs</strong>, associated with your <strong>database</strong>. The app then uses each <strong>DAO</strong> to get <strong>entities</strong> from the <strong>database</strong> and save any changes to those <strong>entities</strong> back to the <strong>database</strong>. Finally, the app uses an <strong>entity</strong> to get and set values that correspond to table columns within the <strong>database</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kpBhJHwNOExLpnEI.png" /></figure><h3>Database</h3><p>As mentioned earlier, it contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data. The class that’s annotated with <a href="https://developer.android.com/reference/androidx/room/Database">@Database</a> should satisfy the following conditions:</p><ul><li>Be an abstract class that extends <a href="https://developer.android.com/reference/androidx/room/RoomDatabase">RoomDatabase</a>.</li><li>Include the list of entities associated with the database within the annotation.</li><li>Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao</li><li>At runtime, you can acquire an instance of <a href="https://developer.android.com/reference/androidx/room/Database">Database</a> by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder()</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa7d13734823b24f8f1ba0454d356486/href">https://medium.com/media/fa7d13734823b24f8f1ba0454d356486/href</a></iframe><p>To get an instance of the database, you can use the following method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8f3cf19f810e75bc8c5556a98ecb656/href">https://medium.com/media/d8f3cf19f810e75bc8c5556a98ecb656/href</a></iframe><blockquote><strong><em>Note: </em></strong><em>If your app runs in a single process, you should follow the singleton design pattern when instantiating a </em><strong><em>RoomDatabase</em></strong><em> object. Each </em><strong><em>RoomDatabase</em></strong><em> instance is fairly expensive, and you rarely need access to multiple instances within a single process.</em></blockquote><h3>Entity</h3><p>Entity represents a table within a database. This class is annotated with @Entity annotation. Data members in this class represent the columns within a table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe3fa3246e13f7283ca0cdf79af6526/href">https://medium.com/media/3fe3fa3246e13f7283ca0cdf79af6526/href</a></iframe><ul><li>All the fields in an entity must either be public or have getter &amp; setter methods.</li><li>Entity class should have an empty constructor (if all fields are accessible) or a parameterized constructor which takes all the fields. Room can also use partial constructors.</li><li>Each entity class must have atleast one primary key. You can use either @PrimaryKey annotation to define single field primary key or <a href="https://developer.android.com/reference/androidx/room/Entity#primaryKeys()">primaryKeys</a> attribute of @Entity annotation for multiple fields. You can also use <a href="https://developer.android.com/reference/androidx/room/PrimaryKey#autoGenerate()">autoGenerate</a> property of @PrimaryKey annotation to automatically assign primary keys.</li></ul><pre>@Entity(primaryKeys = arrayOf(&quot;firstName&quot;, &quot;lastName&quot;))</pre><ul><li>By default, Room uses the class name as the database table name. If you want the table to have a different name, set the <a href="https://developer.android.com/reference/androidx/room/Entity#tableName()">tableName</a> property of the <a href="https://developer.android.com/reference/androidx/room/Entity">@Entity</a> annotation. Similarly, you can use the name property of the <a href="https://developer.android.com/reference/androidx/room/Entity">@</a>ColumnInfo annotation for defining the name of columns.</li></ul><pre>@Entity(tableName = &quot;users&quot;)</pre><ul><li>If you don’t want to persist any field, you can annotate them using <a href="https://developer.android.com/reference/androidx/room/Ignore">@Ignore</a>.</li></ul><pre>@Ignore val picture: Bitmap?</pre><ul><li>You can use the indices property of @Entity annotation to add indices to an entity. Also, you can create unique indices by setting the <a href="https://developer.android.com/reference/androidx/room#unique()">unique</a> property of an <a href="https://developer.android.com/reference/androidx/room">@Index</a> annotation to true.</li></ul><pre>@Entity(indices = arrayOf(Index(value = [&quot;last_name&quot;, &quot;address&quot;])))@Entity(indices = arrayOf(Index(value = [&quot;first_name&quot;, &quot;last_name&quot;],<br>        unique = true)))</pre><h3>Data Access Object (DAO)</h3><p>DAOs provide an api for accessing the database. This is an interface which is annotated with @Dao annotation. All the methods in this interface are used for getting data from the database or making changes to the database. These methods are annotated with annotations like @Query, @Insert, @Delete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e907afe3b4db8c40e0f63bd3c3e97ecf/href">https://medium.com/media/e907afe3b4db8c40e0f63bd3c3e97ecf/href</a></iframe><blockquote><strong><em>Note:</em></strong><em> All queries using UserDao are made on the caller thread. So you should take care that no method is invoked from the UI(main) thread.</em></blockquote><h3>Type Converters</h3><p>Sometimes, you might need to persist a custom data type in a single database column. You can use type converters for these types of use cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a367e3c940f95a6a28a8fddec6e57a35/href">https://medium.com/media/a367e3c940f95a6a28a8fddec6e57a35/href</a></iframe><p>Next, you have to add the <a href="https://developer.android.com/reference/androidx/room/TypeConverters">@TypeConverters</a> annotation to the RoomDatabase class so that Room can use the converter that you&#39;ve defined for each <a href="https://developer.android.com/training/data-storage/room/defining-data">entity</a> and <a href="https://developer.android.com/training/data-storage/room/accessing-data">DAO</a> in that RoomDatabase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/801a6ce4f23d14c4cc1f33ab662b7a73/href">https://medium.com/media/801a6ce4f23d14c4cc1f33ab662b7a73/href</a></iframe><p>Thank You !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7c340d0fbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/introduction-to-room-persistent-library-in-android-5d7c340d0fbc">Introduction to Room Persistent Library in Android</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Access Objects — DAO in Room]]></title>
            <link>https://medium.com/mindorks/data-access-objects-dao-in-room-3d108d6b4b54?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d108d6b4b54</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Sat, 23 May 2020 12:07:42 GMT</pubDate>
            <atom:updated>2020-05-24T09:41:24.557Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Data Access Objects — DAO in Room</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJznZzhs0mD0ZM8PSwXwSw.png" /></figure><blockquote><strong>Note:</strong> This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:</blockquote><ul><li><a href="https://medium.com/@deepanshu42/introduction-to-room-persistent-library-in-android-5d7c340d0fbc">Introduction to Room Persistent Library in Android</a></li><li><strong>Data Access Objects — DAO in Room [You are here]</strong></li><li><a href="https://medium.com/@deepanshu42/entity-relationship-in-room-b61cfcbf395">Entity Relationship in Room</a></li><li><a href="https://medium.com/@deepanshu42/how-does-room-work-internally-c17572b03bed">How does Room work internally?</a></li><li><a href="https://medium.com/@deepanshu42/room-database-migrations-35a57bdd0ce6">Room Database Migrations</a></li><li><a href="https://medium.com/@deepanshu42/using-room-with-live-data-and-other-third-party-libraries-18000fe017b2">Using Room with LiveData and other third-party libraries</a></li></ul><h3>Room — Data Access Objects(DAO)</h3><p>In previous articles, we have covered how we can use Room persistence library to create a relational database very easily. Some of the advantages of using Room are compile-time query verification, no boilerplate code and easy integration with RxJava, LiveData and Kotlin Coroutines. All these advantages in Room are achieved using Data Access Objects or DAOs.</p><p>In this article, we going to discuss Data Access Objects or DAOs in detail.</p><p>In Room, Data Access Objects or DAOs are used to access your application’s persisted data. They are a better and modular way to access your database as compared to query builders or direct queries.</p><p>A DAO can be either an interface or an abstract class. If it’s an abstract class, it can optionally have a constructor that takes a <a href="https://developer.android.com/reference/androidx/room/RoomDatabase">RoomDatabase</a> as its only parameter. Room creates each DAO implementation at compile time.</p><p>You can perform multiple operations using DAO like Insertion, Updation, Deletion and making raw queries. Also, you can easily integrate LiveData, RxJava Observables, Kotlin Coroutines in DAOs.</p><h4>Insertion</h4><p>When you create a DAO method and annotate it with <a href="https://developer.android.com/reference/androidx/room/Insert">@Insert</a>, Room generates an implementation that inserts all parameters into the database in a <strong>single transaction.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/612c8ea0e0fe7c421da2064457dd8f9a/href">https://medium.com/media/612c8ea0e0fe7c421da2064457dd8f9a/href</a></iframe><p>onConflict annotation parameter signifies what to do if a conflict happens on insertion. It can take the following values:</p><ul><li><strong>OnConflictStrategy.REPLACE</strong> : To replace the old data and continue the transaction.</li><li><strong>OnConflictStrategy.ROLLBACK</strong> : To rollback the transaction.</li><li><strong>OnConflictStrategy.ABORT</strong> : To abort the transaction. The transaction is rolled back.</li><li><strong>OnConflictStrategy.FAIL</strong> : To fail the transaction. The transaction is rolled back.</li><li><strong>OnConflictStrategy.NONE</strong> : To ignore the conflict.</li></ul><blockquote><strong>Note: ROLLBACK</strong> and <strong>FAIL</strong> strategies are deprecated. Use <strong>ABORT</strong> instead.</blockquote><h4>Updation</h4><p>When you create a DAO method and annotate it with <a href="https://developer.android.com/reference/androidx/room/Insert">@</a><a href="https://developer.android.com/reference/androidx/room/Update">Update</a>, Room generates an implementation that modifies a set of entities, given as parameters, in the database. It uses a query that matches against the primary key of each entity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccee48cb7b9487a8f0a82ba3ea56dd82/href">https://medium.com/media/ccee48cb7b9487a8f0a82ba3ea56dd82/href</a></iframe><h4>Deletion</h4><p>When you create a DAO method and annotate it with <a href="https://developer.android.com/reference/androidx/room/Insert">@</a><a href="https://developer.android.com/reference/androidx/room/Update">D</a>elete, Room generates an implementation that removes a set of entities, given as parameters, from the database. It uses the primary keys to find the entities to delete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02697258f28a1e1ba92ddfdd20428e8f/href">https://medium.com/media/02697258f28a1e1ba92ddfdd20428e8f/href</a></iframe><h4>Simple queries</h4><p><a href="https://developer.android.com/reference/androidx/room/Query">@Query</a> is the main annotation used in DAO classes. It allows you to perform read/write operations on a database. Each <a href="https://developer.android.com/reference/androidx/room/Query">@Query</a> method is verified at compile time, so if there is a problem with the query, a compilation error occurs instead of a runtime failure.</p><p>Room also verifies the return value of the query such that if the name of the field in the returned object doesn’t match the corresponding column names in the query response, Room alerts you in one of the following two ways:</p><ul><li>It gives a warning if only some field names match.</li><li>It gives an error if no field names match.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f5f76288c5a7c628db4223fa338acd0/href">https://medium.com/media/5f5f76288c5a7c628db4223fa338acd0/href</a></iframe><p><strong>Passing parameters into the query</strong></p><p>Parameters passed to the DAO methods can be used into the query written in @Query annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0247d599d0e2d6f6a70bd0c6485717b/href">https://medium.com/media/c0247d599d0e2d6f6a70bd0c6485717b/href</a></iframe><p><strong>Returning subsets of columns</strong></p><p>You can also return subsets of columns from a query in Room.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa22b46be63032ffb22599cc70c7c931/href">https://medium.com/media/aa22b46be63032ffb22599cc70c7c931/href</a></iframe><p><strong>Direct cursor access</strong></p><p>If your app’s logic requires direct access to the return rows, you can return a <a href="https://developer.android.com/reference/android/database/Cursor">Cursor</a> object from your queries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/703224fef5d079d456148637383e6339/href">https://medium.com/media/703224fef5d079d456148637383e6339/href</a></iframe><p><strong>Querying multiple tables</strong></p><p>Some of your queries might require access to multiple tables to calculate the result. Room allows you to write any query, so you can also join tables. Furthermore, if the response is an observable data type, such as <a href="http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html">Flowable</a> or <a href="https://developer.android.com/reference/androidx/lifecycle/LiveData">LiveData</a>, Room watches all tables referenced in the query for invalidation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39e4f664f7d5287a8979680ecd43c9a1/href">https://medium.com/media/39e4f664f7d5287a8979680ecd43c9a1/href</a></iframe><h4>Query return types</h4><p>Room supports a variety of return types for query methods, including specialised return types for interoperability with specific frameworks or APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bQJKPzAPxHgZtYWRWIRXQ.png" /></figure><p>You can return LiveData, Observable and Flow from query methods. Also, you can make a DAO method <strong>suspend function</strong>. These are discussed in separate articles.</p><p>Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d108d6b4b54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/data-access-objects-dao-in-room-3d108d6b4b54">Data Access Objects — DAO in Room</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Relationship in Room]]></title>
            <link>https://medium.com/mindorks/entity-relationship-in-room-b61cfcbf395?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61cfcbf395</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Sat, 23 May 2020 12:07:29 GMT</pubDate>
            <atom:updated>2020-05-24T09:40:33.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJznZzhs0mD0ZM8PSwXwSw.png" /></figure><blockquote><strong>Note:</strong> This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:</blockquote><ul><li><a href="https://medium.com/@deepanshu42/introduction-to-room-persistent-library-in-android-5d7c340d0fbc">Introduction to Room Persistent Library in Android</a></li><li><a href="https://medium.com/@deepanshu42/data-access-objects-dao-in-room-3d108d6b4b54">Data Access Objects — DAO in Room</a></li><li><strong>Entity Relationship in Room [You are here]</strong></li><li><a href="https://medium.com/@deepanshu42/how-does-room-work-internally-c17572b03bed">How does Room work internally?</a></li><li><a href="https://medium.com/@deepanshu42/room-database-migrations-35a57bdd0ce6">Room Database Migrations</a></li><li><a href="https://medium.com/@deepanshu42/using-room-with-live-data-and-other-third-party-libraries-18000fe017b2">Using Room with LiveData and other third-party libraries</a></li></ul><h3>Entity Relationships in Room</h3><p>This article covers how we can define relationship between entities in Room persistence library.</p><p>Since SQLite is a relational database, entities can have relationships between them. In Room, entities cannot directly reference other entities because it might cause loading unnecessary data every time.</p><p>Still sometimes, you would want to reference other entities from your entity. You can acheive this in multiple ways.</p><h4>Embedded Objects</h4><p>You can use the <a href="https://developer.android.com/reference/androidx/room/Embedded">@Embedded</a> annotation to represent an object that you&#39;d like to decompose into its subfields within a table(entity). You can then query the embedded fields just as you would for other individual columns.</p><blockquote>Embedded fields can also include other embedded fields.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6242176c3363467e78d64200c5621d/href">https://medium.com/media/bf6242176c3363467e78d64200c5621d/href</a></iframe><p>The table representing a User object then contains columns with the following names: id, firstName, street, state, city, and postCode.</p><blockquote>If an entity has multiple embedded fields of the same type, you can keep each column unique by setting the <a href="https://developer.android.com/reference/androidx/room/Embedded#prefix()">prefix</a> property. Room then adds the provided value to the beginning of each column name in the embedded object.</blockquote><p>In the above example, fields of an object are decomposed into an entity. In case you want to represent relationship between multiple entities, you cannot use the <a href="https://developer.android.com/reference/androidx/room/Embedded">@Embedded</a> annotation.</p><p>You can use either @Relation annotation or foreignkeys parameter of @Entity annotation for defining relationship between two entities. <br>Both of them are different from each other in such a way that @Relation annotation can only be applied on a non-entity class whereas ForeignKey is used on an entity class. Also, ForeignKey affects the schema of an entity that requires that the child column(s) exist in the parent column(s). @Relation is used to join the tables without affecting the schema of tables.</p><p>You can define relationship between entities in 3 ways:</p><ul><li>One-to-one relationship</li><li>One-to-many relationship or Many-to-one relationship</li><li>Many-to-many relationship</li></ul><h3>One-to-one relationships</h3><p>A <em>one-to-one relationship</em> between two entities is a relationship where each instance of the parent entity corresponds to exactly one instance of the child entity, and vice-versa.</p><p>For example, consider a music streaming app where the user has a library of songs that they own. Each user has only one library, and each library corresponds to exactly one user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da25b72c2f69cecf2bf556bc49bfba75/href">https://medium.com/media/da25b72c2f69cecf2bf556bc49bfba75/href</a></iframe><p>In the above example, User and Library are the entities which have <em>one-to-one relationship. </em>One of the entities must include a variable that is a reference to the primary key of the other entity(userOwnerId in Library entity).</p><p>In order to query the list of users and corresponding libraries, we must first model the one-to-one relationship between the two entities, which is done using UserAndLibrary class. The UserAndLibrary class contains an instance of the parent entity(User) and the corresponding instance of the child entity(Library). Then, add the <a href="https://developer.android.com/reference/kotlin/androidx/room/Relation">@Relation</a> annotation to the instance of the child entity, with <a href="https://developer.android.com/reference/kotlin/androidx/room/Relation#parentcolumn">parentColumn</a> set to the name of the primary key column of the parent entity and <a href="https://developer.android.com/reference/kotlin/androidx/room/Relation#entitycolumn">entityColumn</a> set to the name of the column of the child entity that references the parent entity&#39;s primary key.</p><p>Now we can query our database in the following way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/945bb375b4c2ffffc2561363430e0afc/href">https://medium.com/media/945bb375b4c2ffffc2561363430e0afc/href</a></iframe><blockquote>This method requires Room to run two queries, so add the <a href="https://developer.android.com/reference/kotlin/androidx/room/Transaction">@Transaction</a> annotation to this method to ensure that the whole operation is performed atomically.</blockquote><h3>One-to-many relationships</h3><p>A <em>one-to-many relationship</em> between two entities is a relationship where each instance of the parent entity corresponds to zero or more instances of the child entity, but each instance of the child entity can only correspond to exactly one instance of the parent entity.</p><p>In the previous music streaming app example, a User can have multiple playlists. Each user can create as many playlists as they want, but each playlist is created by exactly one user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/746dc36c7e77c9b1db31179c4e66c86d/href">https://medium.com/media/746dc36c7e77c9b1db31179c4e66c86d/href</a></iframe><p>As we can see, the approach is very similar to <em>one-to-one relationship, </em>the only difference here is in the relationship model(UserWithPlaylists). Instead of containing a single child entity, it now contains a list of child entity. Querying the database is also very similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a06b71ed80b29915ee13cd48866e55a/href">https://medium.com/media/1a06b71ed80b29915ee13cd48866e55a/href</a></iframe><h3>Many-to-many relationships</h3><p>A <em>many-to-many relationship</em> between two entities is a relationship where each instance of the parent entity corresponds to zero or more instances of the child entity, and vice-versa.</p><p>In the music streaming app example, each playlist can include many songs, and each song can be a part of many different playlists. Therefore, there should be a many-to-many relationship between the Playlist entity and the Song entity.</p><p>Many-to-many relationships are distinct from other relationship types because there is generally no reference to the parent entity in the child entity. Instead, a third class is used to represent an <a href="https://en.wikipedia.org/wiki/Associative_entity">associative entity</a> (or cross-reference table) between the two entities. The cross-reference table must have columns for the primary key from each entity in the many-to-many relationship represented in the table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b75b72aa7e3225f0d0130a1ec6cddc7/href">https://medium.com/media/5b75b72aa7e3225f0d0130a1ec6cddc7/href</a></iframe><p>Now, the next step depends on how you want to query these related entities.</p><ul><li>If you want to query <em>playlists</em> and a list of the corresponding <em>songs</em> for each playlist, create a new data class that contains a single Playlist object and a list of all of the Song objects that the playlist includes.</li><li>If you want to query <em>songs</em> and a list of the corresponding <em>playlists</em> for each, create a new data class that contains a single Song object and a list of all of the Playlist objects in which the song is included.</li></ul><p>In either case, model the relationship between the entities by using the associateBy property in the @Relation annotation in each of these classes to identify the cross-reference entity providing the relationship between the Playlist entity and the Song entity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c837f6db65c09327ddd1319957e5602d/href">https://medium.com/media/c837f6db65c09327ddd1319957e5602d/href</a></iframe><p>Querying the database is similar to the previous approaches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8cd24635b6ca7b0ec26d2d8b9483f2c/href">https://medium.com/media/a8cd24635b6ca7b0ec26d2d8b9483f2c/href</a></iframe><p>That’s all about the entity relationships in Room. Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61cfcbf395" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/entity-relationship-in-room-b61cfcbf395">Entity Relationship in Room</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does Room work internally?]]></title>
            <link>https://medium.com/mindorks/how-does-room-work-internally-c17572b03bed?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17572b03bed</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Sat, 23 May 2020 12:07:19 GMT</pubDate>
            <atom:updated>2020-05-24T09:41:33.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJznZzhs0mD0ZM8PSwXwSw.png" /></figure><blockquote><strong>Note:</strong> This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:</blockquote><ul><li><a href="https://medium.com/@deepanshu42/introduction-to-room-persistent-library-in-android-5d7c340d0fbc">Introduction to Room Persistent Library in Android</a></li><li><a href="https://medium.com/@deepanshu42/data-access-objects-dao-in-room-3d108d6b4b54">Data Access Objects — DAO in Room</a></li><li><a href="https://medium.com/@deepanshu42/entity-relationship-in-room-b61cfcbf395">Entity Relationship in Room</a></li><li><strong>How does Room work internally? [You are here]</strong></li><li><a href="https://medium.com/@deepanshu42/room-database-migrations-35a57bdd0ce6">Room Database Migrations</a></li><li><a href="https://medium.com/@deepanshu42/using-room-with-live-data-and-other-third-party-libraries-18000fe017b2">Using Room with LiveData and other third-party libraries</a></li></ul><h3>How Room works internally?</h3><p>In the previous articles, we discussed how we can use Room library (part of Google’s <a href="https://developer.android.com/jetpack">Jetpack</a> project) to create relational persistence in Android applications. Room makes it very easy for a developer to setup a database and start using it in production.</p><p>In this article, we are going to focus on how Room accomplishes all these things.</p><p><a href="https://github.com/deepanshu42/room-example-app">deepanshu42/room-example-app</a></p><p>We are going to use this project as reference for explaining how Room actually does everything. Following are the highlights of our project:</p><ul><li>It has a single database(<strong>UserDatabase</strong>) which contains only one table/entity(<strong>User</strong>).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa7d13734823b24f8f1ba0454d356486/href">https://medium.com/media/fa7d13734823b24f8f1ba0454d356486/href</a></iframe><ul><li><strong>User</strong> table has 3 columns: <strong>uid</strong>, <strong>first name</strong> and <strong>last name</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe3fa3246e13f7283ca0cdf79af6526/href">https://medium.com/media/3fe3fa3246e13f7283ca0cdf79af6526/href</a></iframe><ul><li><strong>UserDao </strong>is the interface through which our application interacts with the database.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcbaa9a03a34964e672c0cf11fbc3d9d/href">https://medium.com/media/bcbaa9a03a34964e672c0cf11fbc3d9d/href</a></iframe><h3>Internal Working of Room</h3><p>After creating a Room Database, the first time you compile your code, Room autogenerates implementation of your @Database and @Dao annotated classes. In the above example, implementation of UserDatabase and UserDao is autogenerated by Room annotation processor.</p><blockquote><strong>Note:</strong> You can find the autogenerated code in build/generated/source/kapt/ folder.</blockquote><p>In our example, implementation of UserDatabase is named as UserDatabase_Impl and implementation of UserDao is named as UserDao_Impl. These are the classes where actual processing happens. Let’s discuss both of the implementations individually.</p><h4>UserDatabase_Impl</h4><p>An overview of <strong>UserDatabase_Impl</strong> looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ead619d729644e778e6513dc37044da/href">https://medium.com/media/7ead619d729644e778e6513dc37044da/href</a></iframe><ul><li>createOpenHelper() is invoked when you build instance of your database using Room.databaseBuilder().build(). It creates and returns an instance of SupportSQLiteOpenHelper which is a helper class for managing database creation and version management.</li><li>createInvalidationTracker() creates an invalidation tracker which keeps a list of tables modified by queries and notifies its callbacks about these tables.</li><li>clearAllTables() implements the behaviour of deleting data from all the tables of the specified database.</li><li>userDao() creates(if not exists) and returns the instance of UserDao_Impl for interacting with the users table.</li></ul><h4><strong>UserDao_Impl</strong></h4><p>UserDao_Impl implements all the methods in UserDao. The overview of UserDao_Impl looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62f6fc83a5274293713c90a656f032e5/href">https://medium.com/media/62f6fc83a5274293713c90a656f032e5/href</a></iframe><p>In the above example, UserDao_Impl has 3 fields: <strong>__db, __insertionAdapterOfUser </strong>and<strong> __deletionAdapterOfUser.</strong></p><ul><li><strong>__db </strong>is an instance of RoomDatabase which is used for multiple purposes like transaction and querying the database.</li><li><strong>__insertionAdapterOfUser </strong>is an instance of EntityInsertionAdapter used for inserting entities into a table. This is used in insertAll() method.</li><li><strong>__deletionAdapterOfUser </strong>is an instance of EntityDeletionOrUpdateAdapter used to update/delete entities from a table. This is used in delete() method.</li></ul><h4>Building the RoomDatabase</h4><p>Till now, we have understood what happens after our project is successfully compiled. Also we know that we need an instance of UserDatabase which gives us an instance of UserDao in order to perform any database related operations.</p><p>To get an instance of UserDatabase, Room provides us a builder method named Room.databaseBuilder which gives us an instance of RoomDatabase.Builder. We can use this instance to get UserDatabase by invoking the build() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8f3cf19f810e75bc8c5556a98ecb656/href">https://medium.com/media/d8f3cf19f810e75bc8c5556a98ecb656/href</a></iframe><p>We can use this builder to configure our database like</p><ul><li>createFromAsset()/createFromFile() to create and open database from an asset(located in the application ‘assets/’ folder)/a pre-packaged database file.</li><li>addMigrations() to add database migration from one version to another. A migration is needed whenever we are changing the version of our database even if there is no change in schema of both versions.</li><li>allowMainThreadQueries() to allow making database queries from main thread. By default, Room doesn’t allow this.</li><li>fallbackToDestructiveMigration() allows Room to destructively recreate database tables if migration is not found.</li></ul><p>There are also many other methods provided in RoomDatabase.Builder for database configuration.</p><p>Once we invoke build() method on thisRoomDatabase.Builder instance, Room validates and creates an instance of the autogenerated implementation of UserDatabase::<strong>class</strong>.java — i.e., UserDatabase_Impl. After the creation of UserDatabase_Impl, init() method is invoked on the database by passing the database configuration which in turn invokes the createOpenHelper() method of UserDatabase_Impl.</p><p>Now we are going to discuss the implementation of some important methods in UserDatabase_Impl and UserDao_Impl discussed earlier.</p><h4>userDao() in UserDatabase_Impl</h4><pre>@Override<br><strong>public </strong>UserDao userDao() {<br>  <strong>if </strong>(<strong>_userDao </strong>!= <strong>null</strong>) {<br>    <strong>return _userDao</strong>;<br>  } <strong>else </strong>{<br>    <strong>synchronized</strong>(<strong>this</strong>) {<br>      <strong>if</strong>(<strong>_userDao </strong>== <strong>null</strong>) {<br>        <strong>_userDao </strong>= <strong>new </strong>UserDao_Impl(<strong>this</strong>);<br>      }<br>      <strong>return _userDao</strong>;<br>    }<br>  } <br>}</pre><p>It lazily creates the implementation of UserDao — i.e., UserDao_Impl and returns it whenever userDao() is invoked. As we can see, it passes the instance of RoomDatabase in UserDao_Impl’s constructor.</p><h4>insertAll() in UserDao_Impl</h4><pre>@Override<br><strong>public void </strong>insertAll(<strong>final </strong>User... users) {<br>  <strong>__db</strong>.assertNotSuspendingTransaction();<br>  <strong>__db</strong>.beginTransaction();<br>  <strong>try </strong>{<br>    <strong>__insertionAdapterOfUser</strong>.insert(users);<br>    <strong>__db</strong>.setTransactionSuccessful();<br>  } <strong>finally </strong>{<br>    <strong>__db</strong>.endTransaction();<br>  }<br>}</pre><p>It uses <strong>__db </strong>for creating the transaction and <strong>__insertionAdapterOfUser </strong>for insertion.</p><h4>delete() in UserDao_Impl</h4><pre>@Override<br><strong>public void </strong>delete(<strong>final </strong>User user) {<br>  <strong>__db</strong>.assertNotSuspendingTransaction();<br>  <strong>__db</strong>.beginTransaction();<br>  <strong>try </strong>{<br>    <strong>__deletionAdapterOfUser</strong>.handle(user);<br>    <strong>__db</strong>.setTransactionSuccessful();<br>  } <strong>finally </strong>{<br>    <strong>__db</strong>.endTransaction();<br>  }<br>}</pre><p>It uses <strong>__db </strong>for creating the transaction and <strong>__deletionAdapterOfUser </strong>for deletion.</p><h4>getAll() in UserDao_Impl</h4><pre>@Override<br><strong>public </strong>List&lt;User&gt; getAll() {<br>  <strong>final </strong>String _sql = <strong>&quot;SELECT * FROM users&quot;</strong>;<br>  <strong>final </strong>RoomSQLiteQuery _statement = RoomSQLiteQuery.<em>acquire</em>(_sql, 0);<br>  <strong>__db</strong>.assertNotSuspendingTransaction();<br>  <strong>final </strong>Cursor _cursor = DBUtil.<em>query</em>(<strong>__db</strong>, _statement, <strong>false</strong>, <strong>null</strong>);<br>  <strong>try </strong>{<br>    <strong>final int </strong>_cursorIndexOfUid = CursorUtil.<em>getColumnIndexOrThrow</em>(_cursor, <strong>&quot;uid&quot;</strong>);<br>    <strong>final int </strong>_cursorIndexOfFirstName = CursorUtil.<em>getColumnIndexOrThrow</em>(_cursor, <strong>&quot;first_name&quot;</strong>);<br>    <strong>final int </strong>_cursorIndexOfLastName = CursorUtil.<em>getColumnIndexOrThrow</em>(_cursor, <strong>&quot;last_name&quot;</strong>);<br>    <strong>final </strong>List&lt;User&gt; _result = <strong>new </strong>ArrayList&lt;User&gt;(_cursor.getCount());<br>    <strong>while</strong>(_cursor.moveToNext()) {<br>      <strong>final </strong>User _item;<br>      <strong>final int </strong>_tmpUid;<br>      _tmpUid = _cursor.getInt(_cursorIndexOfUid);<br>      <strong>final </strong>String _tmpFirstName;<br>      _tmpFirstName = _cursor.getString(_cursorIndexOfFirstName);<br>      <strong>final </strong>String _tmpLastName;<br>      _tmpLastName = _cursor.getString(_cursorIndexOfLastName);<br>      _item = <strong>new </strong>User(_tmpUid,_tmpFirstName,_tmpLastName);<br>      _result.add(_item);<br>    }<br>    <strong>return </strong>_result;<br>  } <strong>finally </strong>{<br>    _cursor.close();<br>    _statement.release();<br>  }<br>}</pre><p>As we can see, it creates a RoomSQLiteQuery object from the query specified in @Query annotation. It then simply creates a <strong>cursor</strong> to fetch data from the database.</p><p>This is enough to get a basic understanding of how Room works internally.</p><p>Thank you!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17572b03bed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/how-does-room-work-internally-c17572b03bed">How does Room work internally?</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Room Database Migrations]]></title>
            <link>https://medium.com/mindorks/room-database-migrations-35a57bdd0ce6?source=rss-2dda604e8c19------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a57bdd0ce6</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Deepanshu]]></dc:creator>
            <pubDate>Sat, 23 May 2020 12:07:16 GMT</pubDate>
            <atom:updated>2020-05-24T09:41:43.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJznZzhs0mD0ZM8PSwXwSw.png" /></figure><blockquote><strong>Note:</strong> This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:</blockquote><ul><li><a href="https://medium.com/@deepanshu42/introduction-to-room-persistent-library-in-android-5d7c340d0fbc">Introduction to Room Persistent Library in Android</a></li><li><a href="https://medium.com/@deepanshu42/data-access-objects-dao-in-room-3d108d6b4b54">Data Access Objects — DAO in Room</a></li><li><a href="https://medium.com/@deepanshu42/entity-relationship-in-room-b61cfcbf395">Entity Relationship in Room</a></li><li><a href="https://medium.com/@deepanshu42/how-does-room-work-internally-c17572b03bed">How does Room work internally?</a></li><li><strong>Room Database Migrations [You are here]</strong></li><li><a href="https://medium.com/@deepanshu42/using-room-with-live-data-and-other-third-party-libraries-18000fe017b2">Using Room with LiveData and other third-party libraries</a></li></ul><h3>Room Database Migrations</h3><p>Database migration is a very important concept in any application development. As we add and change features in your app, we have to update schema of our database. Whenever there is a change in the schema of any of our tables, we need to write a migration for the existing application if we don’t want our users to lose all of their existing data.</p><p>For example, we can consider a table named users which contains information of users and it has 3 columns named uid, first_name and last_name. Now if we add a new column for age, we need to write a migration for altering the current table schema — i.e., adding a new column named age.</p><p>The <a href="https://developer.android.com/training/data-storage/room">Room persistence library</a> allows us to write <a href="https://developer.android.com/reference/androidx/room/migration/Migration">Migration</a> classes to preserve user data in this manner. Each <a href="https://developer.android.com/reference/androidx/room/migration/Migration">Migration</a> class specifies a startVersion and endVersion. At runtime, Room runs each <a href="https://developer.android.com/reference/androidx/room/migration/Migration">Migration</a> class&#39;s <a href="https://developer.android.com/reference/androidx/room/migration/Migration#migrate(android.arch.persistence.db.SupportSQLiteDatabase)">migrate()</a> method, using the correct order to migrate the database to a later version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99b46e323c967c2c5e45ddaea51fc6cd/href">https://medium.com/media/99b46e323c967c2c5e45ddaea51fc6cd/href</a></iframe><p>Now we have created the migration object MIGRATION_1_2, we need to add it in the database configuration using database builder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df2d3f95bbcd21d35b1d2c7a4afdc808/href">https://medium.com/media/df2d3f95bbcd21d35b1d2c7a4afdc808/href</a></iframe><h4>Gracefully handle missing migration paths</h4><p>After updating our database’s schemas, it’s possible that some on-device databases could still use an older schema version. If Room cannot find a migration rule for upgrading that device’s database from the older version to the current version, it throws an <a href="https://developer.android.com/reference/java/lang/IllegalStateException">IllegalStateException</a> which makes our app to crash.</p><p>To prevent the app from crashing when this situation occurs, call the fallbackToDestructiveMigration() builder method when creating the database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02930b67c56a1d0e02ea46edd474c76f/href">https://medium.com/media/02930b67c56a1d0e02ea46edd474c76f/href</a></iframe><p>The destructive recreation fallback logic includes several additional options:</p><ul><li>If errors occur in specific versions of your schema history that you cannot solve with migration paths, use <a href="https://developer.android.com/reference/androidx/room/RoomDatabase.Builder#fallbacktodestructivemigrationfrom">fallbackToDestructiveMigrationFrom()</a>. This method indicates that you&#39;d like Room to use the fallback logic only in cases where the database attempts to migrate from one of those problematic versions.</li><li>To perform a destructive recreation only when attempting a schema downgrade, use <a href="https://developer.android.com/reference/androidx/room/RoomDatabase.Builder#fallbacktodestructivemigrationondowngrade">fallbackToDestructiveMigrationOnDowngrade()</a> instead.</li></ul><p>Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a57bdd0ce6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/room-database-migrations-35a57bdd0ce6">Room Database Migrations</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>