<?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 Dan Meng on Medium]]></title>
        <description><![CDATA[Stories by Dan Meng on Medium]]></description>
        <link>https://medium.com/@danmeng_44632?source=rss-a2d06b0c621d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bo_06ZPsmbAJEwSOYsWIEg.jpeg</url>
            <title>Stories by Dan Meng on Medium</title>
            <link>https://medium.com/@danmeng_44632?source=rss-a2d06b0c621d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:36:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danmeng_44632/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[Swift vs Kotlin]]></title>
            <link>https://medium.com/@danmeng_44632/swift-vs-kotlin-e5efa29752f0?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5efa29752f0</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 16:27:27 GMT</pubDate>
            <atom:updated>2022-07-21T15:00:01.205Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is aiming to help an Android developer get a quick knowledge of the Swift programming language. (Writing from this perspective.)</p><p>I didn’t mean to write a very long and detailed article to cover everything, just a quick one to get you onboarded.</p><p>This article is also suitable for:</p><ul><li>Experienced programmer (who knows other programming languages) wants to learn Swift.</li><li>iOS developer (who knows Swift) wants to learn Kotlin.</li><li>iOS beginner developers.</li><li>Developer hasn’t used Swift for a while and wants to get a quick refresher memo.</li></ul><h3>Basic types</h3><figure><img alt="Swift vs Kotlin: basic types" src="https://cdn-images-1.medium.com/max/482/1*PJtYaq7-UIa_oOLtnISkFA.png" /><figcaption>Swift vs Kotlin: basic types</figcaption></figure><p>Other types are basically the same.</p><h3>Syntax</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sFzQBgkXXJMFX5I8PZQVw.png" /><figcaption>Swift vs Kotlin: Syntax</figcaption></figure><h3>Constants and Variables</h3><p>Swift:</p><ul><li>let you can not assign value again. If the type is struct, you can not update any var properties of the instance. (If it&#39;s a class, then you can update var properties).</li><li>var can both assign values or update properties of the instance.</li><li>var also makes an array mutable.</li></ul><p>Kotlin:</p><ul><li>val means final in java, you can not assign values again, but you can update the public vars of the instance.</li><li>var means you can assign values again.</li><li>collections types’ immutable or mutable are controlled by the data type.</li></ul><h3>Switch case</h3><p>Swift:</p><pre>var x = 3<br>switch x {<br>    case 1: print(&quot;x == 1&quot;)<br>    case 2, 4: print(&quot;x == 2 or x == 4&quot;)<br>    default: print(&quot;x is something else&quot;)  <br>}</pre><p>Kotlin:</p><pre>val x = 3<br>when (x) {<br>    1 -&gt; print(&quot;x == 1&quot;)<br>    2, 4 -&gt; print(&quot;x == 2 or x == 4&quot;)<br>    else -&gt; print(&quot;x is something else&quot;)<br>}</pre><h3>String interpolation</h3><p>Swift:</p><pre>var name = &quot;Mike&quot;<br>print(&quot;Hello \(name)&quot;)</pre><p>The string can also be output in a format:</p><pre>let str = NSString(format:&quot;%d , %f, %ld, %@&quot;, 1, 1.5, 100, &quot;Hello World&quot;)<br>print(str)</pre><p>Kotlin:</p><pre>var name = &quot;Mike&quot;<br>println(&quot;Hello $name&quot;)</pre><p>if you want to specify format:</p><pre>val str = String.format(&quot;%d, %f, %d, %s&quot;, 1, 1.5, 100, &quot;Hello World&quot;)<br>print(str)</pre><h3>Function and Closure</h3><p>The Swift function has an argument label:</p><pre>func someFunction(argumentLabel parameterName: Int) {<br>    // In the function body, parameterName refers to the argument value<br>    // for that parameter.<br>}</pre><p>while parameterName is used inside the function, argumentLabel is used by the caller.</p><p>When an argument label is not provided, parameterName also plays the role of argumentLabel.</p><p>If you don’t want to specify an argument label at all, the argument label can be omitted by using underscored _.</p><h3>Closure</h3><p>Closure is similar to lambda in Kotlin.</p><p>A simple Swift example:</p><pre>let sayHello = { (name: String) -&gt; String in<br>    let result = &quot;Hello \(name)&quot;<br>    print(result)<br>    return result<br>}</pre><pre>sayHello(&quot;Mike&quot;)</pre><p>Do the same thing in Kotlin:</p><pre>val sayHello : (String) -&gt; String = { name: String -&gt; <br>    val result = &quot;Hello $name&quot;<br>    print(result)<br>    result<br>}</pre><pre>sayHello(&quot;Mike&quot;)</pre><p>Common:</p><ul><li>The type can be inferred from the context.</li><li>Can be passed as arguments as another function’s parameter to achieve nested functions (high-order functions).</li><li>if the closure/lambda is the last parameter, we can put it outside the function’s parentheses. if it’s the only parameter, we don’t need to write parentheses().</li></ul><p>Differences:</p><ul><li>In Swift, only single expression closure can omitting the return keyword; In Kotlin, the last expression will be treated as the return value, no return keyword in lambda.</li><li>Swift has shorthand argument names such as $0, $1, $2.</li></ul><h3>Custom types</h3><figure><img alt="Swift vs Kotlin: custom types" src="https://cdn-images-1.medium.com/max/428/1*xxxBfs_q-UXI4SAzWsRkAg.png" /><figcaption>Swift vs Kotlin: custom types</figcaption></figure><h3>class</h3><p>The class of Swift and Kotlin looks quite the same.</p><p>The inheritance is using : and the subclass function could override the super class&#39;s function.</p><p>There is an order requirement: the class need to be put before any protocols.</p><p>The only thing different is the constructor, in swift it’s initializer:</p><pre>class Person {<br>    let name: String<br>    init(name: String = &quot;&quot;) {<br>        self.name = name<br>    }<br>}<br>let p1 = Person()<br>print(&quot;\(p1.name)&quot;) // default name: &quot;&quot;</pre><pre>let p2 = Person(name: &quot;haha&quot;)<br>print(&quot;\(p2.name)&quot;)</pre><p>In Kotlin, we could achieve the same result by writing like this:</p><pre>class Person(val name: String = &quot;&quot;) {<br>}<br>val p1 = Person()<br>print(&quot;${p1.name}&quot;) // default name: &quot;&quot;</pre><pre>val p2 = Person(name=&quot;haha&quot;)<br>print(&quot;${p2.name}&quot;)</pre><p>and in Kotlin, class can have an init {} block to help with more initializing work.</p><h3>struct</h3><p>Struct is value type.</p><p>struct vs class:</p><ul><li>class can inherit.</li><li>struct is value type, copies never share data; class is reference type, all copies will share the same instance.</li><li>class has deinit.</li><li>class instance can be let , and you can change the var property of the class.</li></ul><pre>class Person {<br>    var name = &quot;Lily&quot;<br>}</pre><pre>let p1 = Person()<br>p1.name = &quot;Justin&quot;</pre><pre>print(&quot;\(p1.name)&quot;)</pre><p>This is ok.</p><p>But if Person is a struct:</p><pre>struct Person {<br>    var name = &quot;Lily&quot;<br>}</pre><pre>let p1 = Person()<br>p1.name = &quot;Justin&quot;<br>// Compiler error: Cannot assign to property: `p1` is a `let` constant</pre><p>When using struct, we have to use **var** p1 = Person().</p><h3>protocol</h3><p>protocol is just like interface in Kotlin.</p><p>We could define function and properties as contracts.</p><p>The properties could be:</p><pre>protocol SomeProtocol {<br>    var mustBeSettable: Int { get set }<br>    var doesNotNeedToBeSettable: Int { get }<br>}</pre><p>There are slight differences in protocol and interface, like the class implementing the protocol doesn’t need to use the override keyword on functions.</p><h3>extension</h3><p>extension is also different. In Swift, extension is more like a place to hold the functions and properties.</p><pre>extension String {<br>    func trimmed() -&gt; String {<br>        self.trimmingCharacters(in: .whitespacesAndNewlines)<br>    }<br>    <br>    mutating func trim() {<br>        self = self.trimmed()<br>    }<br>    <br>    var lines: [String] {<br>        self.components(separatedBy: .newlines)<br>    }<br>}</pre><p>In Kotlin the extension method could be the top level method, just add the type before .:</p><pre>fun String.someMethod() : String {<br>    return this.trim()<br>}</pre><h3>enum</h3><p>Swift enum:</p><pre>enum CompassPoint {<br>    case north<br>    case south<br>    case east<br>    case west<br>}</pre><p>Multiple cases can be put in one line, separated by comma:</p><pre>enum Planet {<br>    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune<br>}</pre><p>When using the enum, we can drop the type using a shorter dot syntax:</p><pre>var directionToHead = CompassPoint.west<br>directionToHead = .east</pre><p>Swift enum has an allCases property, which exposes a collection of all the cases.</p><p>Kotlin:</p><pre>enum class Direction {<br>    NORTH, SOUTH, WEST, EAST<br>}</pre><p>In enum we can also define properties and functions, which is the same for Swift and Kotlin.</p><h3>Optionals</h3><p>While the syntax of Swift’s optional type and Kotlin’s nullable type looks similar (a question mark following the type), they are different.</p><p>Swift’s optional type is more like Java’s Optional.</p><p>You will always need to unwrap it before using the value.</p><pre>var someString : String? = nil<br>print(someString?.count) // print nil<br>print(someString!.count) // Fatal error: Unexpectedly found nil while unwrapping an Optional value</pre><p>When the variable has value, we want to use it:</p><pre>var someString : String? = &quot;Hello&quot;</pre><pre>if (someString != nil) {<br>    print(&quot;\(someString) with length \(someString?.count)&quot;)<br>    // print: Optional(&quot;Hello&quot;) with length Optional(5)<br>    <br>    print(&quot;\(someString!) with length \(someString!.count)&quot;)<br>    // print: Hello with length 5<br>}</pre><p>Note that when used directly, the variable will always be an Optional.</p><p>Actually in Swift there is a simpler way to do this, using if let:</p><pre>if let someStringValue = someString {<br>    print(&quot;\(someStringValue) with length \(someStringValue.count)&quot;)<br>}</pre><p>The someStringValue is the unwrapped value from someString, and the block is only entered when it&#39;s not nil.</p><p>In Kotlin:</p><pre>var someString : String? = null<br>print(someString?.length) // print null<br>print(someString!!.length) // NullPointerException</pre><p>The difference is mainly when the variable has value:</p><pre>var someString : String? = &quot;Hello&quot;<br>if(someString != null) {<br>   print(&quot;$someString with length: ${someString.length}&quot;)  <br>}<br>// print: Hello with length: 5</pre><p>In Kotlin, after we check the variable is not null, we could use the value directly, in the following code inside {} , the compiler knows the variable is not null.</p><h3>If let and guard let</h3><p>As we see in the above sample in the Optional section, the if let can unwrap the Optional value, and only execute the block when it has value.</p><p>The guard let does the opposite: the else block will be entered only when the value is nil .</p><pre>func printSquare(of number: Int?){<br>    guard let number = number else {<br>        print(&quot;Oops we got nil&quot;)<br>        return<br>    }<br>    <br>    print(&quot;\(number) * \(number) is \(number * number)&quot;)<br>}</pre><p>guard let can be used to do the argument checking and early return.</p><p>After the guard, the number is no longer optional, it has value.</p><h3>Last note</h3><p>I won’t suggest spending much time to learn a language syntax in every detail.</p><p>Just grab some basics and you are ready to go, you will explore more on your daily work.</p><p>Anyway, I hope this article is handy and useful to you.</p><h3>References</h3><ul><li>Swift book: <a href="https://docs.swift.org/swift-book/">https://docs.swift.org/swift-book/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5efa29752f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android navigation with multiple back stacks]]></title>
            <link>https://medium.com/@danmeng_44632/android-navigation-with-multiple-back-stacks-f8585e497a03?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8585e497a03</guid>
            <category><![CDATA[multiple-stacks]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[multi-stack]]></category>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Mon, 20 Jun 2022 17:24:33 GMT</pubDate>
            <atom:updated>2022-06-24T15:53:01.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is multiple stacks</h3><p>When users navigate in the app, they may choose to go back to the previous destination.</p><p>The history is kept as a “back stack” by Android.</p><p>Sometimes we might need to maintain multiple back stacks in the app and switch between them.</p><p>A typical example is for the bottom navigation bar: each tab could have its own back stack, and when switching tabs, the history will be kept.</p><p>You may have a different design such as a side drawer, the idea is the same, but for this article, let’s take bottom navigation as the example.</p><h3>The multi-stack requirements</h3><p>First thing first, let’s get clear about what we need to achieve.</p><p>When the bottom navigation does not support multi-stacks, the behavior is: after switching to another tab and back, all the destinations opened on that tab are gone, only the root destination shown.</p><p>That’s also acceptable, and even mentioned as the default behavior for Android platform in <a href="https://material.io/components/bottom-navigation#behavior">material design</a>.</p><p>But it also claims that it can be overridden when needed.</p><p>If we want to keep whatever user viewed on the previous tab, that’s a multi-stack requirement.</p><p>Often, it may not be the only requirement.</p><p>Do we want to reset the stack when people double-click the tab? Do we want to customize the animations? Do we want to support history between tabs? Like if tab A → B → C, when we are on C’s root screen, do we want to go back to B?</p><p>For the bottom navigation’s default behavior (if you create a new bottom nav example using Android Studio), when on the root level of a tab, when clicking the back button, it will first go back to the home tab (the first tab), and when clicking back again, the app will exit.</p><p>It applies to the fixed start destination principle. But if you have special needs, you might also consider how to customize that.</p><p>When you go deep dive to the implementations, you will also find details on how to push to the specific stack and how to pop destination out.</p><p>Let’s list our requirements here:</p><ul><li>Maintain multiple stacks.</li><li>Switching tabs: by manually clicking tab or some interactions on the other tab. i.e. Dashboard to a specific content tab.</li><li>Push/pop destinations.</li><li>Reselect tab will reset the stack to root level. (clear history.)</li><li>Transition animations.</li><li>Tab history.</li></ul><h3>Technical Background</h3><p>It’s important to know what your “destination” is. For composable or fragments, the solutions could be very different.</p><p>For this article’s scope, let’s focus on a traditional android app built using Activity and Fragments.</p><h3>Fragment lifecycle</h3><p>The fragment’s lifecycle is quite important to check about, as the Fragment’s lifecycle is related to whether we will need to care about state loss or refreshing action, for example, the re-creation of the ViewModel.</p><p>Let’s recap on Fragment’s lifecycle callbacks.</p><p>When would Fragment onDestroy called?</p><ul><li>If the replace transaction is without addToBackStack() .</li><li>when the fragment is removed or popped out by popBackStack().</li></ul><p>When a replace transaction is called with addToBackStack(), the old fragment will be pushed into the stack, and the lifecycle is only reached onDestroyView().</p><p>When the top one popped out from the back stack, the old fragment’s instance is still the same. The come-to-show fragment’s lifecycle starts with onCreateView(). This is what we expected for a single back stack.</p><p>If the project is using ViewModel, the Fragment’s ViewModel’s lifecycle is also aligned with the Fragment. Whenever the Fragment’s onDestroy() is called, the ViewModel’s onCleared() is called.</p><p>We can keep variables we cared about in the saved instance bundle, or by using SavedStateHandle. But if the fragment is not destroyed, we get everything for free.</p><h3>Navigation Libraries/ Possible Solutions</h3><p>To compare different solutions, I put some samples together.</p><p>See my demo: <a href="https://github.com/mengdd/bottom-navigation-samples">https://github.com/mengdd/bottom-navigation-samples</a></p><h3>Jetpack navigation component</h3><p>official site: <a href="https://developer.android.com/guide/navigation">https://developer.android.com/guide/navigation</a></p><p>Even in the FragmentManager’s <a href="https://developer.android.com/guide/fragments/fragmentmanager">doc</a> it’s recommended to use the navigation library to manage app’s navigation.</p><p>The multiple back stack support added in <a href="https://developer.android.com/jetpack/androidx/releases/navigation#2.4.0-alpha01">Navigation 2.4.0-alpha01</a> and <a href="https://developer.android.com/jetpack/androidx/releases/fragment#1.4.0-alpha01">Fragment 1.4.0-alpha01</a>.</p><p>Tried the <a href="https://github.com/mengdd/bottom-navigation-samples/tree/main/navigation-components-multi-stack-sample">demo</a>, it’s quite simple and clean, and the app does not need extra code to get this.</p><p>We can check the ideas in this article: <a href="https://medium.com/androiddevelopers/multiple-back-stacks-b714d974f134">https://medium.com/androiddevelopers/multiple-back-stacks-b714d974f134</a></p><p>Pros:</p><ul><li>Most well-known. It’s the official library built by Google.</li><li>Safe args supported.</li><li>NavigationController supports popping to a specific destination.</li><li>Can work together with the Compose navigation library.</li></ul><p>Cons:</p><ul><li>Multi-stack support: When switching bottom tabs, the fragments on the previous tab will be destroyed, when navigate back, they will all be re-created. The page may be refreshed again.</li><li>Because each tab should be a nested navigation graph, the xml navigation graph files feels like boilerplate code to maintain, especially for common destinations.</li></ul><h3>FragmentManager</h3><p>If we are doing more customization we could also try to build the multi stack solution by using FragmentManager’s new APIs.</p><p>As in this <a href="https://developer.android.com/guide/fragments/fragmentmanager#multiple-back-stacks">doc</a> suggested:</p><blockquote><em>FragmentManager allows you to support multiple back stacks with the </em><em>saveBackStack() and </em><em>restoreBackStack( methods. These methods allow you to swap between back stacks by saving one back stack and restoring a different one.</em></blockquote><p>Here we can find that it’s what navigation component is using under the hood.</p><p>And the why the fragments are all destroyed:</p><blockquote><em>saveBackStack() works similarly to calling </em><em>popBackStack() with the optional </em><em>name parameter: the specified transaction and all transactions after it on the stack are popped. The difference is that </em><em>saveBackStack() saves the state of all fragments in the popped transactions.</em></blockquote><p>Pros:</p><ul><li>Fine control. Developers get more control and are aware of what is going on.</li><li>Proper if we are working on a project without any navigation library. We don’t need to migrate a lot of code to a new navigation library.</li></ul><p>Cons:</p><ul><li>Lots of fragment transaction boilerplate code.</li><li>Same as navigation components: Fragments on the old tab will be destroyed and re-created.</li></ul><h3>Enro</h3><p><a href="https://github.com/isaac-udy/Enro">https://github.com/isaac-udy/Enro</a></p><p>For large projects with multiple modules, I really recommend this navigation library.</p><p>It helps to decouple the modules dependencies.</p><p>For multi-stack demo, see <a href="https://github.com/mengdd/bottom-navigation-samples/tree/main/enro-fragment-multi-stack-sample">here</a>.</p><p>Pros:</p><ul><li>Based on annotation, you only need minimal code to do the navigation, making navigation easy like a breeze.</li><li>Designed for multi-module projects, decoupling modules.</li><li>Can get navigation handle in ViewModel.</li><li>Easy to pass type safe arguments and get results.</li><li>Compose Support.</li><li>Having a companion test tool for Unit Test.</li></ul><p>Cons:</p><ul><li>Not that well-known. Need to convince others to learn and apply this.</li><li>For Fragments’ multi-stack support: can not reset the stack when reselecting the tab. And it is hard to customize this.</li></ul><h3>Simple-stack</h3><p><a href="https://github.com/Zhuinden/simple-stack">https://github.com/Zhuinden/simple-stack</a></p><p>I would suggest this article for the multi-stack solution using simple-stack: <a href="https://zhuinden.medium.com/creating-a-bottomnavigation-multi-stack-using-child-fragments-with-simple-stack-c73c1ca3bbd4">https://zhuinden.medium.com/creating-a-bottomnavigation-multi-stack-using-child-fragments-with-simple-stack-c73c1ca3bbd4</a></p><p>At the beginning the author showed a demo using child fragments.</p><p>This is another idea if we want to implement the multi-stack by ourselves.</p><p>After I tried the multi-stack <a href="https://github.com/mengdd/bottom-navigation-samples/tree/main/simple-stack-multi-stack-sample">demo</a> provided by simple-stack, I found that actually more code is required to let any fragment gain the instance of each tab’s local stack.</p><p>In that way we could push/pop the detail fragment.</p><p>Pros:</p><ul><li>The author is quite active in the community, so there are a bunch of speeches and articles for the simple-stack library. Good community support and learning resources.</li><li>Multi-stack support: keep fragments alive.</li><li>Can control or clear the history.</li><li>Compose Support with extensions.</li></ul><p>Cons:</p><ul><li>If your bottom tab is in an Activity layout, when using simple-stack’s multi-stack solution, you have to move things into a RootFragment.</li><li>The multi-stack sample provided by the author is quite simple. Need to write some code to retrieve the correct stack instance to push/pop a fragment to/from the current stack.</li></ul><h3>Other libraries</h3><p>There are other libraries designed only for multi-stack navigation.</p><p>Such as:</p><ul><li><a href="https://github.com/DimaKron/Android-MultiStacks">https://github.com/DimaKron/Android-MultiStacks</a></li><li><a href="https://github.com/JetradarMobile/android-multibackstack">https://github.com/JetradarMobile/android-multibackstack</a></li></ul><p>The samples are just along the repos.</p><p>Pros:</p><ul><li>Simple solutions with only a few classes. We could even copy them to our codebase to customize.</li><li>The change scope could be limited only to the bottom navigation part.</li></ul><p>Cons:</p><ul><li>The libraries are not so well-known, and have the risk of not being maintained anymore.</li><li>Might not be able to work together with other navigation solutions, like Navigation Components. If the project is aiming to apply some nice navigation library in the future, we have to touch this bottom navigation part again.</li></ul><h3>Conclusions</h3><p>Possible solutions for android multi-stack navigation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQHlC9cToybcONSFUJ6RBg.png" /><figcaption>Multi-stack navigation solutions mentioned in this article</figcaption></figure><p>Note:</p><ul><li><strong>A Completed suite of navigation solution</strong> means the solution can be applied to the whole app as a way to navigate, not just to solve the multi-stack navigation. Here I skipped the ways using Android SDK’s fragment manager or child fragments. Of course in your whole app you can depend on them to do all the navigations.</li><li><strong>Fragment kept</strong>: means the fragments in stack will not be destroyed when pushing back to the back stack, or switching the bottom tabs. Even though the fragments will be recreated after switching back, we need extra work to cache what state we had before.</li></ul><h3>References:</h3><ul><li>Sample: <a href="https://github.com/mengdd/bottom-navigation-samples">https://github.com/mengdd/bottom-navigation-samples</a></li><li>Jetpack Navigation Components: <a href="https://developer.android.com/guide/navigation"><em>https://developer.android.com/guide/navigation</em></a></li><li>Enro: <a href="https://github.com/isaac-udy/Enro"><em>https://github.com/isaac-udy/Enro</em></a></li><li>Simple-stack: <a href="https://github.com/Zhuinden/simple-stack"><em>https://github.com/Zhuinden/simple-stack</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8585e497a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 anti-patterns in Android codebase and why I hate them]]></title>
            <link>https://medium.com/@danmeng_44632/8-anti-patterns-in-android-codebase-and-why-i-hate-them-54923932154a?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54923932154a</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 01:06:46 GMT</pubDate>
            <atom:updated>2022-06-24T16:20:16.722Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we work with the code everyday. Mostly we will be working on some existing code created by others, or as we always like to refer to it as “legacy code”.</p><p>Actually, no matter if the codebase is very old or pretty new, there are always some anti-patterns to complain about. Perfect codebase is quite rare.</p><p>In this article I want to list something I hate most in any android codebase, only biased opinions from a normal developer.</p><p>So feel free to disagree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4YRkJO5bcx9teRS0" /><figcaption>Photo by <a href="https://unsplash.com/@bernardhermant?utm_source=medium&amp;utm_medium=referral">Bernard Hermant</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>№1 No Kotlin</h3><p>If a project is purely java and still in an active development state, I don’t believe it has the ambition to embrace all the new technologies.</p><p>I don’t think working on this project is a good choice for younger developers who are just entering the Android world.</p><p>I would suggest we migrate to Kotlin at least for new features or new code we are touching, bit by bit.</p><p>If we can’t do even this, run from this project.</p><h3>№2 No DI framework</h3><p>Well, it is 2022 already.</p><p>For the Android world, Dependency Injection is not a new topic. In the old days we had dagger, and now Hilt makes things even more easier and simpler.</p><p>If you don’t like to follow Google’s recommendations you could also choose from many third party solutions such as Koin.</p><p>There are so many options to choose from and you like neither of them.</p><p>The consequences may be:</p><ul><li>There are many boilerplate codes just to assemble dependency instances.</li><li>Your singleton instances might be a disaster to look at and maintain.</li><li>If you are using ViewModel, you are writing a lot of Factories to create ViewModels.</li></ul><h3>№3 object with global variables</h3><p>This can be another broader topic whether singleton is a pattern/anti-pattern.</p><p>Yes, singleton is useful.</p><p>Only when you are clear about the boundaries. When you are sure if it’s necessary. Don’t over use it for everything.</p><p>It’s even worse when the object has public vars in it. Everyone at every place can read and write it. Yes, it&#39;s global variables.</p><p>It feels like a key to the devil’s gate.</p><p>You can’t image the tricky usages, and it’s hard to debug and maintain.</p><p>The object is bad for the following reasons:</p><ul><li>It’s hard to be unit tested.</li><li>Sometimes you have to write ugly code to assign value to it and then set it to null.</li></ul><p>It’s only nice when there are only some utilities functions inside it. But in the Kotlin world we also have other choices such as the top-level functions and extensions functions.</p><h3>№4 More than 10 Feature Toggles and A/B Tests</h3><p>If you are a product manager you might have strong reasons for all the feature toggles and A/B Tests. And I’m not challenging the values of them.</p><p>As mentioned from the beginning, I’m just a normal developer who deals with this if-else nightmare.</p><p>Even if I totally understand and agree with the business values, it can not stop me from hating them.</p><p>Implementing new features with the feature toggle could be trivial work as you need to keep everything as before when the toggle is off.</p><p>If developers do this on a large scale, like copying the whole file and giving a different name, there could be some duplications. And other changes (for other features) might need to apply to both versions.</p><p>If developers choose to do this on a small scale, like the if-else on several lines. They have to be precise on every change. There will be multiple if-else.</p><p>Implementing compatibility is not fun. And it generates code smells. If the developer is very patient, he will add unit test cases for both toggle on and off scenarios. But he may also have missed some conditions, if the old code is not test covered. And often, there will be no refactoring. What’s the point of refactoring the code we might not need soon?</p><p>It is also annoying for QA’s work as every feature needs to test more flows, which not only means feature A’s on and off, but also feature B on feature A’s on and off.</p><p>Yup, things would definitely get worse when our feature toggles nested. They just have the complex relationship you need to explain to QA and yourself. If more than 2 feature toggles are nested, I think it’s time to talk to your PO to remove one.</p><h3>№5 Legacy dependencies</h3><p>Some libraries were really popular and now are deprecated.</p><p>I’m looking at you, ButterKnife.</p><p>This is a famous one and I believe it’s quite rare to see it from any android project.</p><p>But in reality we may encounter others.</p><p>Also, there may be some 3rd-party libraries that are not maintained anymore.</p><p>if you have this flag in your gradle.properties:</p><pre>android.enableJetifier=true</pre><p>You can run this task to check if any of your dependencies are still using the legacy support library rather than AndroidX:</p><pre>./gradlew checkJetifier</pre><p>If you find some libraries, I bet they have not been updated for years.</p><p>Please evaluate whether you can find a better replacement.</p><h3>№6 Misused Inheritance</h3><p>It’s really painful to see a codebase that has a bunch of base classes for its Activities, Fragments, and ViewModels.</p><p>A bunch means several, or, a lot.</p><p>For example, between the feature’s Fragment and AndroidX’s Fragment, there may be 2 or 3 parent fragments that play their mysterious roles.</p><p>When a developer wants to add a new Fragment, he might get confused whether to inherit from a base Fragment, and which “base” to use.</p><p>And the same for ViewModel. Do you really need a ViewModel to hold the Loading state and another ViewModel to hold the navigation variable? So a new ViewMoel has to decide if it needs to reuse them all or do things by itself.</p><p>Normally, the BaseFragments and BaseViewModels will have some base type defined as generic types. Or even worse, you have BaseUseCase.</p><p>Please try to get rid of this inheritance net, it makes navigating in IDE harder than before.</p><p>We should minimize the complexity, isn’t it?</p><p>I hope you always remember composition over inheritance.</p><h3>№7 Interface for everything</h3><p>You don’t need interfaces for everything.</p><p>For example, interface for repository, interface for data source. And they are used internally.</p><p>If the interface has only 1 implementation, there is no reason to keep it.</p><p>Maybe some developer designed this for good intention, but we only ended up with a lot of boilerplate code.</p><p>If the other implementation is for the test, let’s review whether it’s a real case or just not using any mock framework yet.</p><h3>№8 EventBus Style</h3><p>EventBus is a famous library. It is also well-known as an anti-pattern, because it’s so free, you can publish one thing and receive it anywhere. Making things unorganized.</p><p>The overuse of EventBus in a codebase could be a disaster. It will decrease the intention to write better structured code.</p><p>Sometimes we are writing “EventBus code” even without actually using the Library. I hope it’s applied only for a few cases, not a common pattern in your codebase.</p><h3>Summing up</h3><p>That’s it for now.</p><p>Hope this article is helpful to you. You may find we are suffering with the same issues. Or you get to know why developers in your team are not that happy or struggling with their hair in hand everyday.</p><p>Let’s make our life easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54923932154a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Hilt works for Android]]></title>
            <link>https://medium.com/@danmeng_44632/how-hilt-works-for-android-ec5547f07cd0?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5547f07cd0</guid>
            <category><![CDATA[id]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[hilts]]></category>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 16:24:17 GMT</pubDate>
            <atom:updated>2021-08-15T16:26:44.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-OOCPGwZWGg32cN" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We had some good old times with the DI library: Dagger.</p><p>Hilt is built on top of Dagger and make it even simpler for use, more user-friendly.</p><p>However, let’s keep in mind what the great tool has done for us. This article will check and log the generated code (step by step) to give us a better understanding.</p><h3>Gradle Setup</h3><p>Just follow the guide to add necessary dependencies. For root build.gradle:</p><pre>buildscript {<br>    ...<br>    ext.hilt_version = &#39;2.38.1&#39;<br>    dependencies {<br>        ...<br>        classpath &quot;com.google.dagger:hilt-android-gradle-plugin:$hilt_version&quot;<br>    }<br>}</pre><p>For app module (and each module):</p><pre>plugins {<br>    id &#39;kotlin-kapt&#39;<br>    id &#39;dagger.hilt.android.plugin&#39;<br>}</pre><pre>android {<br>    ...<br>}</pre><pre>dependencies {<br>    implementation(&quot;com.google.dagger:hilt-android:$hilt_version&quot;)<br>    kapt(&quot;com.google.dagger:hilt-android-compiler:$hilt_version&quot;)<br>}</pre><p>For the time being, Hilt is still using kapt, Which means the annotation processor will generate code in compile time for us. The generated codes are all java code.</p><p>(Maybe in the future the library will use KSP, I heard it will be quicker and more kotlin.)</p><h3>Application</h3><p>As the first step, add @HiltAndroidApp annotation to application class:</p><pre>@HiltAndroidApp<br>class MyAwesomeApplication : Application()</pre><p>After build, several files will be generated under the app/build/generated/source/kapt folder.</p><ul><li>Hilt_MyAwesomeApplication:</li></ul><pre>/**<br> * A generated base class to be extended by the @dagger.hilt.android.HiltAndroidApp annotated class. If using the Gradle plugin, this is swapped as the base class via bytecode transformation.<br> */<br>public abstract class Hilt_MyAwesomeApplication extends Application implements GeneratedComponentManagerHolder {<br>  private final ApplicationComponentManager componentManager = new ApplicationComponentManager(new ComponentSupplier() {<br>    @Override<br>    public Object get() {<br>      return DaggerMyAwesomeApplication_HiltComponents_SingletonC.builder()<br>          .applicationContextModule(new ApplicationContextModule(Hilt_MyAwesomeApplication.this))<br>          .build();<br>    }<br>  });</pre><pre>  @Override<br>  public final ApplicationComponentManager componentManager() {<br>    return componentManager;<br>  }</pre><pre>  @Override<br>  public final Object generatedComponent() {<br>    return this.componentManager().generatedComponent();<br>  }</pre><pre>  @CallSuper<br>  @Override<br>  public void onCreate() {<br>    // This is a known unsafe cast, but is safe in the only correct use case:<br>    // MyAwesomeApplication extends Hilt_MyAwesomeApplication<br>    ((MyAwesomeApplication_GeneratedInjector) generatedComponent()).injectMyAwesomeApplication(UnsafeCasts.&lt;MyAwesomeApplication&gt;unsafeCast(this));<br>    super.onCreate();<br>  }<br>}</pre><p>This will be replaced as the application class. Knowledge we get here:</p><ul><li>The component is generated in the onCreate().</li><li>The ApplicationContextModule provides us @ApplicationContext and Application.</li></ul><pre>@Module<br>@InstallIn(SingletonComponent.class)<br>public final class ApplicationContextModule {<br>  private final Context applicationContext;</pre><pre>  public ApplicationContextModule(Context applicationContext) {<br>    this.applicationContext = applicationContext;<br>  }</pre><pre>  @Provides<br>  @ApplicationContext<br>  Context provideContext() {<br>    return applicationContext;<br>  }</pre><pre>  @Provides<br>  Application provideApplication() {<br>    return Contexts.getApplication(applicationContext);<br>  }<br>}</pre><ul><li>MyAwesomeApplication_ComponentTreeDeps is an empty class annotated by @ComponentTreeDeps.</li><li>MyAwesomeApplication_GeneratedInjector is like this:</li></ul><pre>@OriginatingElement(<br>    topLevelClass = MyAwesomeApplication.class<br>)<br>@GeneratedEntryPoint<br>@InstallIn(SingletonComponent.class)<br>public interface MyAwesomeApplication_GeneratedInjector {<br>  void injectMyAwesomeApplication(MyAwesomeApplication myAwesomeApplication);<br>}</pre><ul><li>MyAwesomeApplication_HiltComponents contains: One @Component:</li></ul><pre>@Component(<br>      modules = {<br>          ApplicationContextModule.class,<br>          ActivityRetainedCBuilderModule.class,<br>          ServiceCBuilderModule.class<br>      }<br>  )<br>  @Singleton<br>  public abstract static class SingletonC implements MyAwesomeApplication_GeneratedInjector,<br>      HiltWrapper_ActivityRetainedComponentManager_ActivityRetainedComponentBuilderEntryPoint,<br>      ServiceComponentManager.ServiceComponentBuilderEntryPoint,<br>      SingletonComponent,<br>      GeneratedComponent {<br>  }</pre><p>And several @Subcomponents:</p><pre>@Subcomponent(<br>      modules = {<br>          HiltWrapper_ActivityModule.class,<br>          HiltWrapper_DefaultViewModelFactories_ActivityModule.class,<br>          FragmentCBuilderModule.class,<br>          ViewCBuilderModule.class<br>      }<br>  )<br>  @ActivityScoped<br>  public abstract static class ActivityC implements ActivityComponent,<br>      DefaultViewModelFactories.ActivityEntryPoint,<br>      HiltWrapper_HiltViewModelFactory_ActivityCreatorEntryPoint,<br>      FragmentComponentManager.FragmentComponentBuilderEntryPoint,<br>      ViewComponentManager.ViewComponentBuilderEntryPoint,<br>      GeneratedComponent {<br>    @Subcomponent.Builder<br>    abstract interface Builder extends ActivityComponentBuilder {<br>    }<br>  }</pre><p>And several modules:</p><pre>@Module(<br>      subcomponents = ActivityC.class<br>  )<br>  @DisableInstallInCheck<br>  abstract interface ActivityCBuilderModule {<br>    @Binds<br>    ActivityComponentBuilder bind(ActivityC.Builder builder);<br>  }</pre><p>Note:</p><ul><li>These are all the components you can refer to in the @InstallIn annotation.</li><li>These components are all the types where you can perform field injection.</li><li>DaggerMyAwesomeApplication_HiltComponents_SingletonC contains all kinds of builders.</li></ul><pre>public final class DaggerMyAwesomeApplication_HiltComponents_SingletonC extends MyAwesomeApplication_HiltComponents.SingletonC {<br>  private final ApplicationContextModule applicationContextModule;</pre><pre>  private final DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC = this;</pre><pre>  private DaggerMyAwesomeApplication_HiltComponents_SingletonC(<br>      ApplicationContextModule applicationContextModuleParam) {<br>    this.applicationContextModule = applicationContextModuleParam;</pre><pre>  }</pre><pre>  public static Builder builder() {<br>    return new Builder();<br>  }</pre><pre>  @Override<br>  public void injectMyAwesomeApplication(MyAwesomeApplication myAwesomeApplication) {<br>  }</pre><p>It extends the MyAwesomeApplication_HiltComponents.SingletonC. Which is the only @Component from MyAwesomeApplication_HiltComponents.</p><h3>@AndroidEntryPoint for Activity</h3><p>Add @AndroidEntryPoint to MainActivity, after build, we got:</p><ul><li>Hilt_MainActivity. Here we could know the injection happens in:</li></ul><pre>private void _initHiltInternal() {<br>    addOnContextAvailableListener(new OnContextAvailableListener() {<br>      @Override<br>      public void onContextAvailable(Context context) {<br>        inject();<br>      }<br>    });<br>  }</pre><ul><li>MainActivity_GeneratedInjector.</li><li>_com_ddmeng_howhiltworks_MainActivity_GeneratedInjector.</li><li>The subcomponent of ActivityC (in MyAwesomeApplication_HiltComponents) also updated: public abstract static class ActivityC implements MainActivity_GeneratedInjector.</li></ul><h3>Constructor Bindings</h3><h3>@Inject on constructor</h3><p>Add one dependency with @Inject on constructor:</p><pre>class AnalyticsService @Inject constructor()</pre><p>A factory will be generated for it:</p><pre>public final class AnalyticsService_Factory implements Factory&lt;AnalyticsService&gt; {<br>  @Override<br>  public AnalyticsService get() {<br>    return newInstance();<br>  }</pre><pre>  public static AnalyticsService_Factory create() {<br>    return InstanceHolder.INSTANCE;<br>  }</pre><pre>  public static AnalyticsService newInstance() {<br>    return new AnalyticsService();<br>  }</pre><pre>  private static final class InstanceHolder {<br>    private static final AnalyticsService_Factory INSTANCE = new AnalyticsService_Factory();<br>  }<br>}</pre><p>And we inject this in our MainActivity:</p><pre>@Inject<br>    lateinit var analytics: AnalyticsService</pre><p>A new file MainActivity_MembersInjector will be generated:</p><pre>public final class MainActivity_MembersInjector implements MembersInjector&lt;MainActivity&gt; {<br>  private final Provider&lt;AnalyticsService&gt; analyticsProvider;</pre><pre>  public MainActivity_MembersInjector(Provider&lt;AnalyticsService&gt; analyticsProvider) {<br>    this.analyticsProvider = analyticsProvider;<br>  }</pre><pre>  public static MembersInjector&lt;MainActivity&gt; create(Provider&lt;AnalyticsService&gt; analyticsProvider) {<br>    return new MainActivity_MembersInjector(analyticsProvider);<br>  }</pre><pre>  @Override<br>  public void injectMembers(MainActivity instance) {<br>    injectAnalytics(instance, analyticsProvider.get());<br>  }</pre><pre>  @InjectedFieldSignature(&quot;com.ddmeng.howhiltworks.MainActivity.analytics&quot;)<br>  public static void injectAnalytics(MainActivity instance, AnalyticsService analytics) {<br>    instance.analytics = analytics;<br>  }<br>}</pre><p>In DaggerMyAwesomeApplication_HiltComponents_SingletonC file: There will be a function like this added:</p><pre>private MainActivity injectMainActivity2(MainActivity instance) {<br>      MainActivity_MembersInjector.injectAnalytics(instance, new AnalyticsService());<br>      return instance;<br>    }</pre><p>The injection also happens at the timing of onContextAvailable:</p><pre>private void _initHiltInternal() {<br>    addOnContextAvailableListener(new OnContextAvailableListener() {<br>      @Override<br>      public void onContextAvailable(Context context) {<br>        inject();<br>      }<br>    });<br>  }</pre><h3>@Inject with @Singleton</h3><p>If we mark it also @Singleton:</p><pre>@Singleton<br>class AnalyticsService @Inject constructor()</pre><p>The generated files AnalyticsService_Factory and MainActivity_MembersInjector will be same as before.</p><p>The only difference would be in: In DaggerMyAwesomeApplication_HiltComponents_SingletonC file:</p><p>These lines are added:</p><pre>...<br>  private Provider&lt;AnalyticsService&gt; analyticsServiceProvider;<br>  private void initialize(final ApplicationContextModule applicationContextModuleParam) {<br>    this.analyticsServiceProvider = DoubleCheck.provider(new SwitchingProvider&lt;AnalyticsService&gt;(singletonC, 0));<br>  }<br>...<br>    private MainActivity injectMainActivity2(MainActivity instance) {<br>      MainActivity_MembersInjector.injectAnalytics(instance, singletonC.analyticsServiceProvider.get());<br>      return instance;<br>    }<br>...</pre><p>Here: DoubleCheck ensure the singleton for us.</p><h3>@Inject with dependencies</h3><p>We could add class with its dependencies as arguments in the constructor:</p><pre>class AnalyticsAdapter @Inject constructor(<br>    private val service: AnalyticsService<br>)</pre><p>The generated factory code will be like:</p><pre>public final class AnalyticsAdapter_Factory implements Factory&lt;AnalyticsAdapter&gt; {<br>  private final Provider&lt;AnalyticsService&gt; serviceProvider;</pre><pre>  public AnalyticsAdapter_Factory(Provider&lt;AnalyticsService&gt; serviceProvider) {<br>    this.serviceProvider = serviceProvider;<br>  }</pre><pre>  @Override<br>  public AnalyticsAdapter get() {<br>    return newInstance(serviceProvider.get());<br>  }</pre><pre>  public static AnalyticsAdapter_Factory create(Provider&lt;AnalyticsService&gt; serviceProvider) {<br>    return new AnalyticsAdapter_Factory(serviceProvider);<br>  }</pre><pre>  public static AnalyticsAdapter newInstance(AnalyticsService service) {<br>    return new AnalyticsAdapter(service);<br>  }<br>}</pre><p>It’s dependency AnalyticsService&#39;s provider will present.</p><p>Same as before, if we mark @Singleton, a provider memeber will be added into DaggerMyAwesomeApplication_HiltComponents_SingletonC:</p><pre>private void initialize(final ApplicationContextModule applicationContextModuleParam) {<br>    this.analyticsServiceProvider = DoubleCheck.provider(new SwitchingProvider&lt;AnalyticsService&gt;(singletonC, 1));<br>    this.analyticsAdapterProvider = DoubleCheck.provider(new SwitchingProvider&lt;AnalyticsAdapter&gt;(singletonC, 0));<br>  }</pre><h3>Module</h3><h3>@Binds</h3><p>If we provide some implementation for an interface using Module and @Binds:</p><pre>interface DataSource {<br>    fun someMethod()<br>}</pre><pre>class DataSourceImpl @Inject constructor(<br>) : DataSource {<br>    override fun someMethod() {<br>    }<br>}</pre><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>abstract class DataModule {</pre><pre>    @Binds<br>    abstract fun bindDataSource(<br>        dataSourceImpl: DataSourceImpl<br>    ): DataSource<br>}</pre><p>This file is added:</p><pre>@AggregatedDeps(<br>    components = &quot;dagger.hilt.android.components.ActivityComponent&quot;,<br>    modules = &quot;com.ddmeng.howhiltworks.DataModule&quot;<br>)<br>public class _com_ddmeng_howhiltworks_DataModule {<br>}</pre><p>Note we use @InstallIn(ActivityComponent::class) in the module. Also a factory DataSourceImpl_Factory is generated for DataSourceImpl, as we use @Inject in its constructor.</p><p>After we inject it for field in activity:</p><pre>@Inject<br>    lateinit var dataSource: DataSource</pre><p>In MainActivity_MembersInjector will show:</p><pre>private final Provider&lt;DataSource&gt; dataSourceProvider;</pre><p>and in DaggerMyAwesomeApplication_HiltComponents_SingletonC:</p><pre>private MainActivity injectMainActivity2(MainActivity instance) {<br>      MainActivity_MembersInjector.injectAnalytics(instance, singletonC.analyticsAdapterProvider.get());<br>      MainActivity_MembersInjector.injectDataSource(instance, new DataSourceImpl());<br>      return instance;<br>    }</pre><p>If we use @Singleton, will add a provider field, the same thing has been mentioned above.</p><h3>@Provides</h3><p>If we setup Module with @Provides:</p><pre>interface Tool {<br>    fun someMethod()<br>}</pre><pre>class ToolImpl @Inject constructor(<br>) : Tool {<br>    override fun someMethod() {<br>    }<br>}</pre><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>object ToolModule {</pre><pre>    @Provides<br>    fun provideTool(): Tool {<br>        return ToolImpl()<br>    }<br>}</pre><p>A ToolImpl_Factory will be generated. Also a ToolModule_ProvideToolFactory:</p><pre>public final class ToolModule_ProvideToolFactory implements Factory&lt;Tool&gt; {<br>  @Override<br>  public Tool get() {<br>    return provideTool();<br>  }</pre><pre>  public static ToolModule_ProvideToolFactory create() {<br>    return InstanceHolder.INSTANCE;<br>  }</pre><pre>  public static Tool provideTool() {<br>    return Preconditions.checkNotNullFromProvides(ToolModule.INSTANCE.provideTool());<br>  }</pre><pre>  private static final class InstanceHolder {<br>    private static final ToolModule_ProvideToolFactory INSTANCE = new ToolModule_ProvideToolFactory();<br>  }<br>}</pre><p>And the injecting member code will become:</p><pre>private MainActivity injectMainActivity2(MainActivity instance) {<br>      MainActivity_MembersInjector.injectAnalytics(instance, singletonC.analyticsAdapterProvider.get());<br>      MainActivity_MembersInjector.injectDataSource(instance, new DataSourceImpl());<br>      MainActivity_MembersInjector.injectTool(instance, ToolModule_ProvideToolFactory.provideTool());<br>      return instance;<br>    }</pre><h3>Scope</h3><p>Noted as we mark the module @InstallIn(ActivityComponent::class), the bindings inside can not be marked as @Singleton (the compiler will report error), we can mark it @ActivityScoped:</p><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>object ToolModule {</pre><pre>    @ActivityScoped<br>    @Provides<br>    fun provideTool(): Tool {<br>        return ToolImpl()<br>    }<br>}</pre><p>After that, in DaggerMyAwesomeApplication_HiltComponents_SingletonC, the tool is provided this way:</p><pre>private MainActivity injectMainActivity2(MainActivity instance) {<br>      MainActivity_MembersInjector.injectAnalytics(instance, singletonC.analyticsAdapterProvider.get());<br>      MainActivity_MembersInjector.injectDataSource(instance, new DataSourceImpl());<br>      MainActivity_MembersInjector.injectTool(instance, provideToolProvider.get());<br>      return instance;<br>    }</pre><p>And the provider is in ActivityCImpl:</p><pre>private static final class ActivityCImpl extends MyAwesomeApplication_HiltComponents.ActivityC {<br>    private final DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC;</pre><pre>    private final ActivityRetainedCImpl activityRetainedCImpl;</pre><pre>    private final ActivityCImpl activityCImpl = this;</pre><pre>    private Provider&lt;Tool&gt; provideToolProvider;<br>...</pre><pre>    @SuppressWarnings(&quot;unchecked&quot;)<br>    private void initialize(final Activity activityParam) {<br>      this.provideToolProvider = DoubleCheck.provider(new SwitchingProvider&lt;Tool&gt;(singletonC, activityRetainedCImpl, activityCImpl, 0));<br>    }</pre><p>Make it singleton in activity.</p><h3>Qualifiers</h3><p>If we want to provide different implementations for the same type, qualifiers could help. Define the qualifiers:</p><pre>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class LocalSource</pre><pre>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class RemoteSource</pre><p>Use in the module to provide different implementations:</p><pre>@Module<br>@InstallIn(ActivityComponent::class)<br>abstract class DataModule {</pre><pre>    @LocalSource<br>    @Binds<br>    abstract fun bindLocalDataSource(localDataSource: LocalDataSource): DataSource</pre><pre>    @RemoteSource<br>    @Binds<br>    abstract fun bindRemoteDataSource(remoteDataSource: RemoteDataSource): DataSource<br>}</pre><p>And when use them, we have to use the same qualifier to tell which dependency is being injected:</p><pre>@LocalSource<br>    @Inject<br>    lateinit var localSource: DataSource</pre><pre>    @RemoteSource<br>    @Inject<br>    lateinit var remoteSource: DataSource</pre><p>The generated code looks like the implementation type is injected directly, having no relationship with the interface.</p><h3>ViewModel</h3><p>Hilt provides a convenient way to inject ViewModel:</p><pre>@HiltViewModel<br>class ExampleViewModel @Inject constructor(<br>    private val savedStateHandle: SavedStateHandle,<br>    private val repository: ExampleRepository<br>) : ViewModel() {<br>}</pre><p>In activity with @AndroidEntryPoint, we could:</p><pre>private val viewModel: ExampleViewModel by viewModels()</pre><p>The generated codes would be:</p><ul><li>ExampleViewModel_Factory:</li></ul><pre>public final class ExampleViewModel_Factory implements Factory&lt;ExampleViewModel&gt; {<br>  private final Provider&lt;SavedStateHandle&gt; savedStateHandleProvider;</pre><pre>  private final Provider&lt;ExampleRepository&gt; repositoryProvider;</pre><pre>  public ExampleViewModel_Factory(Provider&lt;SavedStateHandle&gt; savedStateHandleProvider,<br>      Provider&lt;ExampleRepository&gt; repositoryProvider) {<br>    this.savedStateHandleProvider = savedStateHandleProvider;<br>    this.repositoryProvider = repositoryProvider;<br>  }</pre><pre>  @Override<br>  public ExampleViewModel get() {<br>    return newInstance(savedStateHandleProvider.get(), repositoryProvider.get());<br>  }</pre><pre>  public static ExampleViewModel_Factory create(Provider&lt;SavedStateHandle&gt; savedStateHandleProvider,<br>      Provider&lt;ExampleRepository&gt; repositoryProvider) {<br>    return new ExampleViewModel_Factory(savedStateHandleProvider, repositoryProvider);<br>  }</pre><pre>  public static ExampleViewModel newInstance(SavedStateHandle savedStateHandle,<br>      ExampleRepository repository) {<br>    return new ExampleViewModel(savedStateHandle, repository);<br>  }<br>}</pre><ul><li>File ExampleViewModel_HiltModules with 2 modules:</li></ul><pre>@OriginatingElement(<br>    topLevelClass = ExampleViewModel.class<br>)<br>public final class ExampleViewModel_HiltModules {<br>  private ExampleViewModel_HiltModules() {<br>  }</pre><pre>  @Module<br>  @InstallIn(ViewModelComponent.class)<br>  public abstract static class BindsModule {<br>    private BindsModule() {<br>    }</pre><pre>    @Binds<br>    @IntoMap<br>    @StringKey(&quot;com.ddmeng.howhiltworks.ExampleViewModel&quot;)<br>    @HiltViewModelMap<br>    public abstract ViewModel binds(ExampleViewModel vm);<br>  }</pre><pre>  @Module<br>  @InstallIn(ActivityRetainedComponent.class)<br>  public static final class KeyModule {<br>    private KeyModule() {<br>    }</pre><pre>    @Provides<br>    @IntoSet<br>    @HiltViewModelMap.KeySet<br>    public static String provide() {<br>      return &quot;com.ddmeng.howhiltworks.ExampleViewModel&quot;;<br>    }<br>  }<br>}</pre><ul><li>And a factory ExampleViewModel_HiltModules_KeyModule_ProvideFactory for the KeyModule:</li></ul><pre>public final class ExampleViewModel_HiltModules_KeyModule_ProvideFactory implements Factory&lt;String&gt; {<br>  @Override<br>  public String get() {<br>    return provide();<br>  }</pre><pre>  public static ExampleViewModel_HiltModules_KeyModule_ProvideFactory create() {<br>    return InstanceHolder.INSTANCE;<br>  }</pre><pre>  public static String provide() {<br>    return Preconditions.checkNotNullFromProvides(ExampleViewModel_HiltModules.KeyModule.provide());<br>  }</pre><pre>  private static final class InstanceHolder {<br>    private static final ExampleViewModel_HiltModules_KeyModule_ProvideFactory INSTANCE = new ExampleViewModel_HiltModules_KeyModule_ProvideFactory();<br>  }<br>}</pre><p>In DaggerMyAwesomeApplication_HiltComponents_SingletonC:</p><pre>private static final class ViewModelCImpl extends MyAwesomeApplication_HiltComponents.ViewModelC {<br>    private final SavedStateHandle savedStateHandle;</pre><pre>    private final DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC;</pre><pre>    private final ActivityRetainedCImpl activityRetainedCImpl;</pre><pre>    private final ViewModelCImpl viewModelCImpl = this;</pre><pre>    private Provider&lt;ExampleViewModel&gt; exampleViewModelProvider;</pre><pre>    private ViewModelCImpl(DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC,<br>        ActivityRetainedCImpl activityRetainedCImpl, SavedStateHandle savedStateHandleParam) {<br>      this.singletonC = singletonC;<br>      this.activityRetainedCImpl = activityRetainedCImpl;<br>      this.savedStateHandle = savedStateHandleParam;<br>      initialize(savedStateHandleParam);</pre><pre>    }</pre><pre>    private ExampleViewModel exampleViewModel() {<br>      return new ExampleViewModel(savedStateHandle, new ExampleRepository());<br>    }</pre><pre>    @SuppressWarnings(&quot;unchecked&quot;)<br>    private void initialize(final SavedStateHandle savedStateHandleParam) {<br>      this.exampleViewModelProvider = new SwitchingProvider&lt;&gt;(singletonC, activityRetainedCImpl, viewModelCImpl, 0);<br>    }</pre><pre>    @Override<br>    public Map&lt;String, Provider&lt;ViewModel&gt;&gt; getHiltViewModelMap() {<br>      return Collections.&lt;String, Provider&lt;ViewModel&gt;&gt;singletonMap(&quot;com.ddmeng.howhiltworks.ExampleViewModel&quot;, (Provider) exampleViewModelProvider);<br>    }</pre><pre>    private static final class SwitchingProvider&lt;T&gt; implements Provider&lt;T&gt; {<br>      private final DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC;</pre><pre>      private final ActivityRetainedCImpl activityRetainedCImpl;</pre><pre>      private final ViewModelCImpl viewModelCImpl;</pre><pre>      private final int id;</pre><pre>      SwitchingProvider(DaggerMyAwesomeApplication_HiltComponents_SingletonC singletonC,<br>          ActivityRetainedCImpl activityRetainedCImpl, ViewModelCImpl viewModelCImpl, int id) {<br>        this.singletonC = singletonC;<br>        this.activityRetainedCImpl = activityRetainedCImpl;<br>        this.viewModelCImpl = viewModelCImpl;<br>        this.id = id;<br>      }</pre><pre>      @SuppressWarnings(&quot;unchecked&quot;)<br>      @Override<br>      public T get() {<br>        switch (id) {<br>          case 0: // com.ddmeng.howhiltworks.ExampleViewModel <br>          return (T) viewModelCImpl.exampleViewModel();</pre><pre>          default: throw new AssertionError(id);<br>        }<br>      }<br>    }<br>  }</pre><p>And in the same file’s ActivityCImpl: ViewModel is not injected same way as before.</p><pre>@Override<br>    public DefaultViewModelFactories.InternalFactoryFactory getHiltInternalFactoryFactory() {<br>      return DefaultViewModelFactories_InternalFactoryFactory_Factory.newInstance(ApplicationContextModule_ProvideApplicationFactory.provideApplication(singletonC.applicationContextModule), getViewModelKeys(), new ViewModelCBuilder(singletonC, activityRetainedCImpl));<br>    }</pre><pre>    @Override<br>    public Set&lt;String&gt; getViewModelKeys() {<br>      return Collections.&lt;String&gt;singleton(ExampleViewModel_HiltModules_KeyModule_ProvideFactory.provide());<br>    }</pre><pre>    @Override<br>    public ViewModelComponentBuilder getViewModelComponentBuilder() {<br>      return new ViewModelCBuilder(singletonC, activityRetainedCImpl);<br>    }</pre><h3>Inject ViewModel in Activity</h3><p>In the above example, we use field injection for ViewModel (in Activity). The function is from activity-ktx:</p><pre>@MainThread<br>public inline fun &lt;reified VM : ViewModel&gt; ComponentActivity.viewModels(<br>    noinline factoryProducer: (() -&gt; Factory)? = null<br>): Lazy&lt;VM&gt; {<br>    val factoryPromise = factoryProducer ?: {<br>        defaultViewModelProviderFactory<br>    }</pre><pre>    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)<br>}</pre><h3>Inject ViewModel in Fragment</h3><p>For fragment, we also have functions from fragment-ktx:</p><pre>@AndroidEntryPoint<br>class FragmentA : Fragment() {<br>    private val viewModel: ExampleViewModel by viewModels()<br>    private val sharedViewModel: ExampleViewModel by activityViewModels()  <br>}</pre><p>The source code:</p><pre>@MainThread<br>public inline fun &lt;reified VM : ViewModel&gt; Fragment.viewModels(<br>    noinline ownerProducer: () -&gt; ViewModelStoreOwner = { this },<br>    noinline factoryProducer: (() -&gt; Factory)? = null<br>): Lazy&lt;VM&gt; = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)</pre><pre>@MainThread<br>public inline fun &lt;reified VM : ViewModel&gt; Fragment.activityViewModels(<br>    noinline factoryProducer: (() -&gt; Factory)? = null<br>): Lazy&lt;VM&gt; = createViewModelLazy(<br>    VM::class, { requireActivity().viewModelStore },<br>    factoryProducer ?: { requireActivity().defaultViewModelProviderFactory }<br>)</pre><pre>@MainThread<br>public fun &lt;VM : ViewModel&gt; Fragment.createViewModelLazy(<br>    viewModelClass: KClass&lt;VM&gt;,<br>    storeProducer: () -&gt; ViewModelStore,<br>    factoryProducer: (() -&gt; Factory)? = null<br>): Lazy&lt;VM&gt; {<br>    val factoryPromise = factoryProducer ?: {<br>        defaultViewModelProviderFactory<br>    }<br>    return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)<br>}</pre><h3>Inject ViewModel in Compose</h3><p>In compose, after we add androidx.lifecycle:lifecycle-viewmodel-compose:$version dependency, we could inject viewModel like this:</p><pre>@Composable<br>fun HomeScreen() {<br>    val viewModel: ExampleViewModel = viewModel()<br>}</pre><p>The source code:</p><pre>@Composable<br>public inline fun &lt;reified VM : ViewModel&gt; viewModel(<br>    viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {<br>        &quot;No ViewModelStoreOwner was provided via LocalViewModelStoreOwner&quot;<br>    },<br>    key: String? = null,<br>    factory: ViewModelProvider.Factory? = null<br>): VM = viewModel(VM::class.java, viewModelStoreOwner, key, factory)</pre><pre>public fun &lt;VM : ViewModel&gt; viewModel(<br>    modelClass: Class&lt;VM&gt;,<br>    viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {<br>        &quot;No ViewModelStoreOwner was provided via LocalViewModelStoreOwner&quot;<br>    },<br>    key: String? = null,<br>    factory: ViewModelProvider.Factory? = null<br>): VM = viewModelStoreOwner.get(modelClass, key, factory)</pre><pre>private fun &lt;VM : ViewModel&gt; ViewModelStoreOwner.get(<br>    javaClass: Class&lt;VM&gt;,<br>    key: String? = null,<br>    factory: ViewModelProvider.Factory? = null<br>): VM {<br>    val provider = if (factory != null) {<br>        ViewModelProvider(this, factory)<br>    } else {<br>        ViewModelProvider(this)<br>    }<br>    return if (key != null) {<br>        provider.get(key, javaClass)<br>    } else {<br>        provider.get(javaClass)<br>    }<br>}</pre><p>And when using androidx.navigation:navigation-compose:$version, we could do this:</p><pre>NavHost(<br>        modifier = modifier,<br>        navController = navController,<br>        startDestination = startDestination<br>    ) {<br>        composable(NavDestinations.LOGIN) {<br>        val loginViewModel: LoginViewModel = hiltViewModel()<br>            LoginPage(<br>            // ...<br>            )<br>        }<br>}</pre><p>This is adding another scope (NavBackStackEntry) to ViewModel rather than Activity/Fragment.</p><p>The source code:</p><pre>@Composable<br>inline fun &lt;reified VM : ViewModel&gt; hiltViewModel(<br>    viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {<br>        &quot;No ViewModelStoreOwner was provided via LocalViewModelStoreOwner&quot;<br>    }<br>): VM {<br>    val factory = createHiltViewModelFactory(viewModelStoreOwner)<br>    return viewModel(viewModelStoreOwner, factory = factory)<br>}</pre><pre>@Composable<br>@PublishedApi<br>internal fun createHiltViewModelFactory(<br>    viewModelStoreOwner: ViewModelStoreOwner<br>): ViewModelProvider.Factory? = if (viewModelStoreOwner is NavBackStackEntry) {<br>    HiltViewModelFactory(<br>        context = LocalContext.current,<br>        navBackStackEntry = viewModelStoreOwner<br>    )<br>} else {<br>    // Use the default factory provided by the ViewModelStoreOwner<br>    // and assume it is an @AndroidEntryPoint annotated fragment or activity<br>    null<br>}</pre><h3>EntryPoint</h3><p>Hilt comes with support for the most common Android classes. However, you might need to perform field injection in classes that Hilt doesn’t support.</p><p>In those cases, you can create an entry point using the @EntryPoint annotation. An entry point is the boundary between code that is managed by Hilt and code that is not.</p><pre>@EntryPoint<br>@InstallIn(SingletonComponent::class)<br>interface MyEntryPoint {<br>    fun analyticsService(): AnalyticsService<br>}</pre><p>This will be generated:</p><pre>@AggregatedDeps(<br>    components = &quot;dagger.hilt.components.SingletonComponent&quot;,<br>    entryPoints = &quot;com.ddmeng.howhiltworks.MyEntryPoint&quot;<br>)<br>public class _com_ddmeng_howhiltworks_MyEntryPoint {<br>}</pre><p>And in MyAwesomeApplication_HiltComponents: MyEntryPoint will be added in the interface list:</p><pre>@Singleton<br>  public abstract static class SingletonC implements MyAwesomeApplication_GeneratedInjector,<br>      MyEntryPoint,<br>      HiltWrapper_ActivityRetainedComponentManager_ActivityRetainedComponentBuilderEntryPoint,<br>      ServiceComponentManager.ServiceComponentBuilderEntryPoint,<br>      SingletonComponent,<br>      GeneratedComponent {<br>  }</pre><p>When use it:</p><pre>override fun query(<br>        uri: Uri,<br>        projection: Array&lt;out String&gt;?,<br>        selection: String?,<br>        selectionArgs: Array&lt;out String&gt;?,<br>        sortOrder: String?<br>    ): Cursor? {<br>        val appContext = context?.applicationContext ?: throw IllegalStateException()<br>        val hiltEntryPoint =<br>            EntryPointAccessors.fromApplication(appContext, MyEntryPoint::class.java)</pre><pre>        val analyticsService = hiltEntryPoint.analyticsService()<br>        //...</pre><pre>        return null<br>    }</pre><p>The source code:</p><pre>public static &lt;T&gt; T fromApplication(Context context, Class&lt;T&gt; entryPoint) {<br>    return EntryPoints.get(Contexts.getApplication(context.getApplicationContext()), entryPoint);<br>  }</pre><pre>public final class EntryPoints {<br>  @Nonnull<br>  public static &lt;T&gt; T get(Object component, Class&lt;T&gt; entryPoint) {<br>    if (component instanceof GeneratedComponent) {<br>      if (component instanceof TestSingletonComponent) {<br>        // @EarlyEntryPoint only has an effect in test environment, so we shouldn&#39;t fail in<br>        // non-test cases. In addition, some of the validation requires the use of reflection, which<br>        // we don&#39;t want to do in non-test cases anyway.<br>        Preconditions.checkState(<br>            !hasAnnotationReflection(entryPoint, EARLY_ENTRY_POINT),<br>            &quot;Interface, %s, annotated with @EarlyEntryPoint should be called with &quot;<br>                + &quot;EarlyEntryPoints.get() rather than EntryPoints.get()&quot;,<br>            entryPoint.getCanonicalName());<br>      }<br>      // Unsafe cast. There is no way for this method to know that the correct component was used.<br>      return entryPoint.cast(component);<br>    } else if (component instanceof GeneratedComponentManager) {<br>      return get(((GeneratedComponentManager&lt;?&gt;) component).generatedComponent(), entryPoint);<br>    } else {<br>      throw new IllegalStateException(<br>          String.format(<br>              &quot;Given component holder %s does not implement %s or %s&quot;,<br>              component.getClass(), GeneratedComponent.class, GeneratedComponentManager.class));<br>    }<br>  }<br>}</pre><p>Actually it’s a cast return entryPoint.cast(component); because as mentioned above, The application class: DaggerMyAwesomeApplication_HiltComponents_SingletonC extends MyAwesomeApplication_HiltComponents.SingletonC { and SingletonC implements MyEntryPoint.</p><h3>References</h3><ul><li><a href="https://developer.android.com/training/dependency-injection/hilt-android">Dependency injection with Hilt</a></li><li><a href="https://dagger.dev/hilt/">Hilt</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5547f07cd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The creation of ViewModel]]></title>
            <link>https://medium.com/@danmeng_44632/the-creation-of-viewmodel-767855e2f1a?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/767855e2f1a</guid>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[hilts]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 16:48:40 GMT</pubDate>
            <atom:updated>2021-12-22T15:08:21.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>The creation of ViewModel</h3><p>ViewModel itself is just a subclass of ViewModel:</p><pre>class MainViewModel: ViewModel() {<br>    <br>}</pre><p>How does it have the ability to keep data across screen rotations? When will it get cleared?</p><p>The answers are all related on how we create it.</p><h3>Create ViewModel Manually</h3><p>It’s simple when ViewModel has no arguments:</p><pre>class MainViewModel: ViewModel() {}</pre><pre>class MainActivity : ComponentActivity() {</pre><pre>    private lateinit var viewModel: MainViewModel</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)<br>    }<br>}</pre><p>Note: This can not be done before Activity’s onCreate(), meaning you could not declare and assign it directly. Otherwise you will get this error:</p><pre>Caused by: java.lang.IllegalStateException: Your activity is not yet attached to the Application instance. You can&#39;t request ViewModel before onCreate call.</pre><p>But when ViewModel needs some dependency:</p><pre>class MainViewModel(<br>    private val repository: MainRepository,<br>) : ViewModel()</pre><p>We have to create the dependency by ourselves and pass it to a factory:</p><pre>class MyViewModelFactory constructor(private val repository: MainRepository) :<br>    ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {<br>            return MainViewModel(repository) as T<br>        }<br>        throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}</pre><pre>class MainActivity : ComponentActivity() {</pre><pre>    private lateinit var viewModel: MainViewModel<br>    private val repository: MainRepository = MainRepository()<br>    private val viewModelFactory: MyViewModelFactory = MyViewModelFactory(repository)</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)<br>    }<br>}</pre><h3>AndroidX to the rescue</h3><p>Thanks to the ‘by viewModels()’ Kotlin property delegate from the activity-ktx artifact: The above code could be updated as:</p><pre>class MyViewModelFactory constructor(private val repository: MainRepository) :<br>    ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {<br>            return MainViewModel(repository) as T<br>        }<br>        throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}</pre><pre>class MainActivity : ComponentActivity() {</pre><pre>    private val viewModel: MainViewModel by viewModels {<br>        viewModelFactory<br>    }<br>    private val repository: MainRepository = MainRepository()<br>    private val viewModelFactory: MyViewModelFactory = MyViewModelFactory(repository)</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)</pre><pre>        // use viewModel<br>    }<br>}</pre><p>And it’s simple when ViewModel with no arguments:</p><pre>private val viewModel: MainViewModel by viewModels()</pre><h3>Dagger Time</h3><p>We can annotate constructor with @Inject to tell dagger to create repository and viewModelFactory for us:</p><pre>class MainRepository @Inject constructor(){}</pre><pre>@Singleton<br>class MyViewModelFactory @Inject constructor(private val repository: MainRepository) :<br>    ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {<br>            return MainViewModel(repository) as T<br>        }<br>        throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}</pre><p>But don’t do this for ViewModel, because ViewModel should be stored in the viewModelStore, which provided by activity.</p><p>We would inject viewModelFactory, and then use it to create ViewModel:</p><pre>class MainActivity : ComponentActivity() {</pre><pre>    private val viewModel: MainViewModel by viewModels {<br>        viewModelFactory<br>    }<br>    @Inject<br>    lateinit var viewModelFactory: MyViewModelFactory<br>}</pre><p>And if you are using dagger, not hilt, you would need something like this in your onCreate():</p><pre>(applicationContext as MyApplication).appComponent.inject(this)</pre><h3>Now Hilt</h3><p>Annotate your ViewModel with @HiltViewModel and @Inject:</p><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val repository: MainRepository,<br>) : ViewModel() {<br>}</pre><p>And dependencies still have @Inject:</p><pre>class MainRepository @Inject constructor(){}</pre><p>In Activity, add annotation @AndroidEntryPoint:</p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {</pre><pre>    private val viewModel: MainViewModel by viewModels()</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)</pre><pre>        // use viewModel<br>    }<br>}</pre><p>No factory class and code required.</p><h3>Compose ViewModel()</h3><p>ViewModel in Compose can be obtained easily by using viewModel() function:</p><pre>@Composable<br>fun Greeting(name: String) {<br>    val viewModel: MainViewModel = viewModel()<br>    // use viewModel<br>}</pre><h3>Compose hiltViewModel()</h3><p>Use the hiltViewModel() composable function we could get an instance of ViewModel scoped to the destination.</p><pre>NavHost(navController = navController, startDestination = &quot;friendslist&quot;) {<br>    composable(&quot;friendslist&quot;) {<br>        val viewModel = hiltViewModel&lt;MainViewModel&gt;()<br>        FriendsList(viewModel = viewModel, navHostController = navController)<br>    }<br>    ...<br>}</pre><p>In this way, the ViewModel’s lifecycle will be same with the destination.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767855e2f1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hi, I’m in]]></title>
            <link>https://medium.com/@danmeng_44632/hi-im-in-69d197b0de3e?source=rss-a2d06b0c621d------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d197b0de3e</guid>
            <dc:creator><![CDATA[Dan Meng]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 14:55:40 GMT</pubDate>
            <atom:updated>2021-07-21T15:02:19.519Z</atom:updated>
            <content:encoded><![CDATA[<p>Nice to meet you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8WvnvyArwi43rJtN" /><figcaption>Photo by <a href="https://unsplash.com/@lemonvlad?utm_source=medium&amp;utm_medium=referral">Vladislav Klapin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BasrBcJt3ajHmdO3" /><figcaption>Photo by <a href="https://unsplash.com/@rocknrollmonkey?utm_source=medium&amp;utm_medium=referral">Rock&#39;n Roll Monkey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d197b0de3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>