<?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 Duy Ha on Medium]]></title>
        <description><![CDATA[Stories by Duy Ha on Medium]]></description>
        <link>https://medium.com/@hamanhduy?source=rss-ea61e5aba8fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mxV3Mz4LGlAVcDMCUoOj5A.png</url>
            <title>Stories by Duy Ha on Medium</title>
            <link>https://medium.com/@hamanhduy?source=rss-ea61e5aba8fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:20:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamanhduy/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[Integrate Flutter into the existing native app]]></title>
            <link>https://medium.com/@hamanhduy/integrate-flutter-into-the-existing-native-app-8099ba6f6373?source=rss-ea61e5aba8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8099ba6f6373</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-module]]></category>
            <dc:creator><![CDATA[Duy Ha]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 07:50:06 GMT</pubDate>
            <atom:updated>2025-02-25T16:00:56.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W2uyQugWTpwmoC4B" /><figcaption>Photo by <a href="https://unsplash.com/@lightsabercollection?utm_source=medium&amp;utm_medium=referral">Lightsaber Collection</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You have a native app written in Kotlin for Android and Swift for iOS. You’ve heard about Flutter and want to experiment with it. Maybe you’re considering using Flutter for new features, but you’re unsure if it’s the right choice. This article is for you.</p><h3>1. When to use a Flutter module?</h3><p>Before using a Flutter module, I have a big question for you. Should you create a new Flutter module? Or you continue to use native code. The right answer may meet these conditions:</p><h4><strong>Is this feature a separate screen?</strong></h4><p>Using Flutter for a standalone screen is a best practice. It simplifies communication and navigation, reducing complexity. In this case, the Flutter engine’s lifecycle aligns with the module’s lifecycle.</p><h4><strong>Does this feature need high performance?</strong></h4><p>Flutter excels in UI/UX, but if your feature demands high performance, a cross-platform solution might not be the best fit. Consider this carefully before choosing Flutter.</p><h4>Is development speed a priority?</h4><p>If you need to release a feature quickly, Flutter’s hot reload and cross-platform capabilities can speed up development.</p><h4><strong>Is your team ready for Flutter?</strong></h4><p>Switching to Flutter requires a different mindset. Flutter uses a declarative UI style, so your team needs to be familiar with this approach. However, if your team is eager to learn, this shouldn’t be a problem — Flutter is quite quick to pick up.</p><p>In our case, we have a delivery app and need to develop a brand-new service. Our team is young and enthusiastic about new frameworks, making Flutter a great choice for experimentation.</p><h3>2. Configuration</h3><h4><strong>Module environment configuration</strong></h4><p>To launch a Flutter module within an existing app, you may need the following data:</p><ul><li>token</li><li>refresh token</li><li>environment settings</li><li>other necessary configurations</li></ul><p>This information can be passed from the native code to the Flutter module using a MethodChannel.</p><pre>static const channel = MethodChannel(&quot;channelCommon&quot;);<br>static Future&lt;Map&lt;String, dynamic&gt;?&gt; getConfig() async {<br>  try {<br>    final config = await channel.invokeMethod(&#39;getConfig&#39;);<br>    return jsonDecode(config);<br>  } catch (e) {<br>    logger.e(&quot;Error&quot;, e);<br>    return null;<br>  }<br>}</pre><p>And you can initialize your configuration before launching the Flutter module.</p><pre>final configJson = await PlatformChannel.getConfig();<br>final appConfig = AppConfig.fromJson(configJson);<br>injector.registerSingleton&lt;AppConfig&gt;(appConfig);</pre><p>You can create an AppConfig like this:</p><pre>class AppConfig {<br><br>  final EnvironmentConfig environmentConfig;<br>  String token;<br>  String? refreshToken;<br><br><br>  AppConfig({required this.environmentConfig, required this.token,<br>    required this.refreshToken});<br><br>  factory AppConfig.create(Map&lt;String, dynamic&gt; config) {<br>    final environmentConfig = EnvironmentConfig.create(config[&quot;env&quot;]);<br>    return AppConfig(<br>      environmentConfig: environmentConfig,<br>      token: config[&quot;token&quot;] ?? &quot;&quot;,<br>      refreshToken: config[&quot;refresh_token&quot;]<br>    );<br>  }<br>}</pre><p>Create an EnvironmentConfig base class and derive subclasses based on your development environment. These classes can be used to manage product flavor variables.</p><pre>abstract class EnvironmentConfig {<br>  late String apiBaseUrl;<br><br>  factory EnvironmentConfig.create(String? env) {<br>    if (env == &quot;production&quot;) {<br>      return ProductionEnvironmentConfig();<br>    } else if (env == &quot;staging&quot;) {<br>      return StagingEnvironmentConfig();<br>    } else {<br>      throw Exception(&quot;Invalid env param&quot;);<br>    }<br>  }<br>}<br><br>class ProductionEnvironmentConfig implements EnvironmentConfig {<br><br>  @override<br>  String apiBaseUrl = &quot;https://api.yourhost.com&quot;;<br>}<br><br>class StagingEnvironmentConfig implements EnvironmentConfig {<br><br>  @override<br>  String apiBaseUrl = &quot;https://staging-api.yourhost.com&quot;;<br>}</pre><h3>3. Build and publish to Gitlab maven</h3><p>Build flutter using flutter command line:</p><pre>flutter build aar --no-debug --no-profile</pre><p>The build process generates a local Maven repository. Next, we need to publish this repository to a remote Maven repository. There are many options available, but if you’re using GitLab for code management, the <a href="https://docs.gitlab.com/ee/user/packages/maven_repository/">GitLab Package Registry</a> is a great choice.</p><p>I’ll cover the details in another post, but you can follow the detailed instructions <a href="https://docs.gitlab.com/ee/user/packages/maven_repository/#create-maven-packages-with-gitlab-cicd">here</a>.</p><h3>4. Issues you might face</h3><p>When building an Android library using Flutter, you may encounter several challenges:</p><p><strong>Library version conflicts</strong><br>Conflicts with dependencies like Kotlin, Firebase, or other libraries may cause crashes. Flutter libraries often rely on the latest versions of native dependencies, so you might need to update multiple libraries in your codebase.</p><p><strong>Flutter library issues</strong><br>Integrating a Flutter module into an existing app is often more complex than developing a full Flutter app from scratch. Dependency management becomes trickier, and some Flutter-related issues remain unresolved. (OMG! We faced a crash for several months before finding a workaround.)</p><p><strong>Communication between Flutter and native code</strong><br>You can use MethodChannel to communicate between Flutter and native code, but it’s not as seamless as working entirely in native code.</p><h3>5. Conclusion</h3><p>Now you have some key points to consider when integrating Flutter into an existing app. I’ve used Flutter in several Android app modules, and it has significantly sped up development — especially for UI. While there’s a learning curve at first, once you get familiar with it, you’ll love it!</p><p>Thank you for reading. <strong>Happy coding! 😊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8099ba6f6373" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hilt, Behind the annotation]]></title>
            <link>https://medium.com/@hamanhduy/hilt-behind-the-annotation-1d2f477a3985?source=rss-ea61e5aba8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d2f477a3985</guid>
            <category><![CDATA[android-hilt]]></category>
            <dc:creator><![CDATA[Duy Ha]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 15:14:49 GMT</pubDate>
            <atom:updated>2021-12-24T10:39:25.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ujEX7BADwkLhFouj8QspQ.png" /><figcaption>Photo from <a href="https://developer.android.com/">https://developer.android.com/</a></figcaption></figure><p>Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. Just by several annotations and configs, you can complete the dependency injection. In this post, we will dive into 2 important annotations <a href="https://developer.android.com/training/dependency-injection/hilt-android#android-classes">@AndroidEntryPoint</a> and <a href="https://developer.android.com/training/dependency-injection/hilt-android#component-scopes">@Scope</a>.</p><h3><strong>1. @AndroidEntryPoint</strong></h3><p>It marks the Android component to be set up for injection with Hilt. But how does it work? Let consider the below example:</p><pre>@AndroidEntryPoint<br>class MyActivity : AppCompatActivity() {<br>    @Inject lateinit var myService: MyService<br>}<br><br>class MyService @Inject constructor() {<br>}</pre><p>By using @AndroidEntryPoint and @Inject, we can set up the dependency injection easily. Now, just use Command + click to see what is inside this magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okTnq_p4uS5hsbJEWK0XyA.png" /></figure><p>You can see the Hilt_MyActivity. It is where the injection work. Each Android component marked with @AndroidEntryPoint, Hilt will generate a wrapper Hilt_ class.</p><pre>public abstract class Hilt_MyActivity extends AppCompatActivity implements GeneratedComponentManagerHolder</pre><p>Inside this class, the injection is in inject() function.</p><pre>protected void inject() {<br>  if (!injected) {<br>    injected = true;<br>    ((MyActivity_GeneratedInjector) this.generatedComponent()).injectMyActivity(UnsafeCasts.&lt;MyActivity&gt;<em>unsafeCast</em>(this));<br>  }<br>}</pre><p>First Hilt generates a component, then uses the component to inject MyService instance into MyActivity. It is in MyActivity_MembersInjector.</p><pre>private MyActivity injectMyActivity2(MyActivity instance) {<br>  MyActivity_MembersInjector.injectMyService(instance, new MyService());<br>  return instance;<br>}</pre><p>It calls <a href="https://en.wikipedia.org/wiki/Dependency_injection#:~:text=this.otherService%20%3D%20otherService%3B%0A%7D-,Setter%20injection,-%5Bedit%5D">setter injection</a>. Another injection type is <a href="https://en.wikipedia.org/wiki/Dependency_injection#:~:text=techniques%20described%20below.-,Constructor%20injection,-%5Bedit%5D">constructor injection</a>.</p><pre>public static void injectMyService(MyActivity instance, MyService myService) {<br>  instance.myService = myService;<br>}</pre><p>It basically the same with other Android components. The difference is the component lifecycle for each class. You can see detail <a href="https://developer.android.com/training/dependency-injection/hilt-android#component-hierarchy">here</a>.</p><h3><strong>2. @Scope</strong></h3><p>An important config that many developers don&#39;t know. It is scope. It is the lifecycle of the instance. Basically, when we need an instance of a class, we create a new instance.</p><pre>val myService = MyService()</pre><p>It is no scope. But in some situations, we have to share the instance. It is when we need to define the scope. Hilt defines scopes for each Android component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4lb-WlNBKBIVKUe0wAeQA.png" /></figure><p>Let consider a scope example of Activity.</p><pre>@AndroidEntryPoint<br>class MyActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>my_activity</em>)<br>    }<br>}<br><br>@AndroidEntryPoint<br>class MyFragment1 : Fragment() {<br>    @Inject lateinit var myService: MyService<br>}<br><br>@AndroidEntryPoint<br>class MyFragment2 : Fragment() {<br>    @Inject lateinit var myService: MyService<br>}<br><br>class MyService @Inject constructor() {<br>    init {<br>        Log.d(&quot;MyService&quot;, &quot;Create new instance of MyService&quot;)<br>    }<br>}</pre><p>I use MyFragment1 and MyFragment2 in the my_activity layout. And I add log messages to see if these 2 instance is the same or not. And here is the result.</p><pre>2021–12–19 15:18:08.775 7625–7625/com.duyha.hilttestingsample D/MyService: Create new instance of MyService<br>2021–12–19 15:18:08.775 7625–7625/com.duyha.hilttestingsample D/MyService: Create new instance of MyService</pre><p>Two instances of MyService have been created. Because we don’t mark it with scope. Let use @ActivityScoped.</p><pre>@ActivityScoped<br>class MyService @Inject constructor() {<br>    init {<br>        Log.d(&quot;MyService&quot;, &quot;Create new instance of MyService&quot;)<br>    }<br>}</pre><p>And see the log message.</p><pre>2021–12–19 15:21:06.619 7695–7695/com.duyha.hilttestingsample D/MyService: Create new instance of MyService</pre><p>And that is what we expect. Just only a single instance has been created. We can use a scope to share the instance inside an activity, in this case between 2 fragments. And we can use @Singleton to share only a single instance in whole the application.</p><h3>3. Fragment context is not Activity</h3><p>In the fragment, context sometimes is the Activity that attaches the fragment. And you might see many lines of code that cast the context to the fragment callback likes that.</p><pre><em>context </em>as FragmentCallback</pre><p>With Hilt, it will cause the below exception.</p><pre>dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper cannot be cast to …</pre><p>Because when we use Hilt with Fragment, a Hilt_Fragment class will be generated. It is the same with any Android component that is marked with @AndroidEntryPoint. And in that generated Hilt_Fragment, context is now a ContextWrapper.</p><pre>private ContextWrapper componentContext;<br>@Override<br>public Context getContext() {<br>  if (super.getContext() == null &amp;&amp; componentContext == null) {<br>    return null;<br>  }<br>  initializeComponentContext();<br>  return componentContext;<br>}</pre><p>So, you can not cast the context to the host callback interface. But, how to resolve the problem in case you have code like that. Easy, just assign the call back in the onAttach function.</p><pre>override fun onAttach(context: Context) {<br>    super.onAttach(context)<br>    callback = context as FragmentCallback<br>}</pre><p>Or you can use the ContextWraper.</p><pre>callback = if (<em>context </em>is ContextWrapper)<br>        (<em>context </em>as ContextWrapper).<em>baseContext </em>as FragmentCallback<br>else <em>context </em>as FragmentCallback</pre><p>And you can use the callback when you need it.</p><p>And that’s all for this post. You can see, we can understand the implementation of a library by viewing its code. And it can help us resolve many bugs or problems. We are software engineers, and we need to read code 😎 😎 😎.</p><p>Thank you for reading. And see you in the next post. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d2f477a3985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test your Android MVVM app with Hilt]]></title>
            <link>https://medium.com/@hamanhduy/test-your-android-mvvm-app-with-hilt-2ad583e49f74?source=rss-ea61e5aba8fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad583e49f74</guid>
            <dc:creator><![CDATA[Duy Ha]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 09:20:53 GMT</pubDate>
            <atom:updated>2025-02-24T15:16:20.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing an Android MVVM App with Hilt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEp4qBl9lykLXJ1e8XEovg.jpeg" /><figcaption>Image created by the author using Grok</figcaption></figure><p>Google has officially announced and recommended Hilt as the preferred dependency injection library for Android. Hilt provides a structured framework for dependency injection, making your work easier — you only need to focus on defining and providing the dependencies you need in your graph.</p><p>This post will walk you through a simple example of using Hilt for dependency injection and testing, demonstrating just how easy it is.</p><h3>1. Dependency graph</h3><p>Our sample is a simple calculator app that allows users to input two numbers and display their sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*N8PaQCm_7qtD696BPir8Hg.png" /><figcaption>Calculator App</figcaption></figure><p>In our case, we have a CalculatorScreen (compose view), a corresponding ViewModel, and a UseCase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sw14O8CPtFGOSB9HD-syYg.png" /><figcaption>Dependency Graph</figcaption></figure><h3><strong>2. Provide the dependencies</strong></h3><p>We can provide any dependencies using Hilt’s @Module. This module is where we define and initialize instances of the libraries used in our app. Then, we simply use Hilt to inject the required instances whenever needed.</p><p><strong>AppModule</strong></p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>class AppModule {<br><br>    @Provides<br>    fun provideSumUseCase(): SumUseCase = SumUseCase()<br>}</pre><p>Another way to provide dependencies is by using the @Inject constructor. In this example, I’ll use this approach for a simple configuration. However, for more complex libraries, using a module is a better choice.</p><pre>class SumUseCase @Inject constructor() {}</pre><h3><strong>3. Let’s inject the dependencies</strong></h3><p>Every app that uses Hilt must include an Application class annotated with @HiltAndroidApp.</p><pre>@HiltAndroidApp<br>class App : Application() {<br>}</pre><p>CalculatorViewModel depends on the SumUseCase. We can inject this dependency with the constructor injection.</p><pre>@HiltViewModel<br>class CalculatorViewModel @Inject constructor(<br>    private val calculator: SumUseCase<br>) : ViewModel() {</pre><p>The @HiltViewModel containing a constructor annotated @Inject will have its dependencies defined in the constructor parameters injected by Hilt.</p><p>On the CalculatorActivity, we use @AndroidEntryPoint to mark the activity to be set up for injection with Hilt. And used viewModel() to get the instance of CalculatorViewModel.</p><pre>@AndroidEntryPoint<br>class CalculatorActivity : ComponentActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            CalculatorScreen()<br>        }<br>    }<br>}<br><br>@Preview<br>@Composable<br>fun CalculatorScreen(<br>    viewModel: CalculatorViewModel = viewModel()<br>) {<br>}</pre><h3>4. Testing the ViewModel</h3><p>The ViewModel depends on the UseCase through its constructor, making testing easier.</p><p>First, set up the testing environment by creating a mock UseCase object and passing it to the ViewModel constructor. This allows us to verify any behavior of the ViewModel based on the mock object.</p><pre>@Before<br>fun setUp() {<br>    sumUseCase = mockk()<br>    viewModel = CalculatorViewModel(sumUseCase)<br>}<br><br>@Test<br>fun test_SumReturnFromUseCase_UpdateUiState() = runTest {<br>    //Given<br>    every { sumUseCase.invoke(a, b) } returns  sum<br>    //When<br>    viewModel.onSumClick(textA, textB)<br>    //Then<br>    verify { sumUseCase.invoke(a, b) }<br>    viewModel.uiState.test {<br>        assertEquals(CalculatorUiState.Success(sum), awaitItem())<br>        cancelAndConsumeRemainingEvents()<br>    }<br>}</pre><p>In this example, I use <a href="https://mockk.io/">MockK</a>, a fantastic mocking library for Kotlin.</p><h3>5. Testing the View</h3><p>To run Android instrumented unit tests with Hilt, we first need to create a custom TestRunner:</p><pre>class TestRunner : AndroidJUnitRunner() {<br><br>    override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {<br>        return super.newApplication(cl, HiltTestApplication::class.java.name, context)<br>    }<br>}</pre><p>Then config this test runner in your build.gradle files:</p><pre>android {<br>  defaultConfig {<br>    testInstrumentationRunner &quot;com.duyha.hilttestingsample.TestRunner&quot;<br>  }<br>}</pre><p><strong>Testing strategy</strong></p><p>The UI state is managed within the ViewModel, and the UI updates dynamically based on changes in the UI state. To test the UI, we modify the UI state and verify that the UI behaves as expected.</p><p>To achieve this, we create a mock<strong> </strong>ViewModel and use @BindValue to instruct Hilt to replace the real ViewModel with our mock version in the dependency graph. Since this example uses Jetpack Compose, we also need to configure a composeTestRule first.</p><pre>@HiltAndroidTest<br>@RunWith(AndroidJUnit4::class)<br>class CalculatorScreenTest {<br>    @get:Rule<br>    val composeTestRule = createComposeRule()<br><br>    @BindValue<br>    @JvmField<br>    val viewModel: CalculatorViewModel = mockk(relaxed = true)<br>}</pre><p>Now we can test the View using this mock ViewModel.</p><pre>@Test<br>fun test_SuccessState_ShowSumResult() {<br>    //Given<br>    val uiState: MutableStateFlow&lt;CalculatorUiState&gt; = MutableStateFlow(CalculatorUiState.Initial)<br>    every { viewModel.uiState } returns uiState<br>    composeTestRule.setContent {<br>        CalculatorScreen(viewModel)<br>    }<br>    //When<br>    uiState.value = CalculatorUiState.Success(10)<br>    //Then<br>    composeTestRule.onNodeWithText(&quot;10&quot;).assertIsDisplayed()<br>}</pre><p>If we want to use @BindValue with an instance provided by a module, we should use @UninstallModules to remove the original module from the dependency graph.</p><h3>6. Conclusion</h3><p>With a few configurations, we have completed the dependency injection and testing of the MVVM app. In this example, I use anUseCase, but we won’t focus on testing it here — perhaps that will be covered in another post on clean architecture testing. This time, our focus is on MVVM testing with Hilt.</p><p>Thank you for reading! Feel free to check out my GitHub to download the full version of the code.</p><p><a href="https://github.com/manhduy/hilt-testing-sample">GitHub - manhduy/hilt-testing-sample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad583e49f74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>