<?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 Valery Ponomarenko on Medium]]></title>
        <description><![CDATA[Stories by Valery Ponomarenko on Medium]]></description>
        <link>https://medium.com/@valeroncho?source=rss-aea50bb898c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O1yk35bnjUGaBt8vACxTag.jpeg</url>
            <title>Stories by Valery Ponomarenko on Medium</title>
            <link>https://medium.com/@valeroncho?source=rss-aea50bb898c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:49:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valeroncho/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[Evolving from Software Engineer to Product Engineer]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@valeroncho/evolving-from-software-engineer-to-product-engineer-846205f7a1bf?source=rss-aea50bb898c7------2"><img src="https://cdn-images-1.medium.com/max/1536/1*9ybKwWdji3Xzdejt388mig.png" width="1536"></a></p><p class="medium-feed-snippet">For almost ten years, I have been building mobile applications. App architecture, platform behavior, API integration, performance, and the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@valeroncho/evolving-from-software-engineer-to-product-engineer-846205f7a1bf?source=rss-aea50bb898c7------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@valeroncho/evolving-from-software-engineer-to-product-engineer-846205f7a1bf?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/846205f7a1bf</guid>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[product-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 03:37:43 GMT</pubDate>
            <atom:updated>2026-07-19T03:37:43.303Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Hardest Part of AI-Assisted Coding Is Still Thinking]]></title>
            <link>https://itnext.io/the-hardest-part-of-ai-assisted-coding-is-still-thinking-0bd96f9dcea9?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd96f9dcea9</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 19:30:44 GMT</pubDate>
            <atom:updated>2026-07-10T19:30:44.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4k6sYUTedCrABm7lEjuM-A.png" /></figure><p>I think most of us have had this moment: you type “make it good” into an AI agent, press Enter and get a large piece of code back. It compiles, it looks reasonable in a demo and it may even pass the first review.</p><p>Then, a few weeks later, you need to change it. You open the file and ask yourself: &quot;Wait, who wrote this?&quot;. In a way, you did. But the decisions behind it were mostly made by the agent.</p><p>This article is not about blaming the model. AI agents are useful tools and they can save a lot of time. The problem is the assumption that we can skip the thinking part and let an agent make the important decisions for us.</p><p>We cannot. Let’s look at why.</p><h3>What &quot;make it good&quot; actually gives you</h3><p>The difficult part is that the result often does not look bad.</p><p>If the agent returned obviously broken code, strange names, or inconsistent formatting, it would be easy to reject. But modern agents usually learn enough from the codebase to produce something that looks familiar. It follows existing naming, puts files in sensible folders and creates code that seems acceptable at first glance.</p><p>The problem is often underneath. The agent may introduce a couple of patterns the team never agreed on. It may solve a problem that does not really exist. Or it may build a factory that creates strategies that configure builders, when the boring solution would have been two clear lines of code. This is not Java enterprise. Just write these two lines and that’s it.</p><p>Code can be elegant, clear and easy to understand after one read. It can also be clever in a way that looks impressive but makes the next feature much harder. &quot;Make it good&quot; can easily produce the second kind: code that looks polished in a pull request but becomes difficult to work with later.</p><p>There is an old rule that still works well:</p><blockquote>Write your code as if the person who maintains it is a psycho who knows where you live.</blockquote><p>With AI, there is one more detail. The next person maintaining the code may be an agent with a fresh context window or it may be you six months later with little memory of the original decision. If the code is hard to read, every future task becomes more expensive. The agent needs more context to understand it, you need more time to review its changes and the chance of introducing a regression grows. You might save ten minutes by writing &quot; make it good&quot;. But you will pay for that shortcut every time the code needs to be changed.</p><h3>It is an assistant, not an architect</h3><p>Let’s describe the actual mistake more precisely. When we ask an agent to &quot;make it follow SOLID&quot; we are not only delegating implementation. We are delegating design decisions. SOLID is not a button that can be applied to a feature. It is a set of trade-offs about a particular domain, boundary and future changes.</p><p>The agent knows the language and framework. It can generate patterns very quickly. But it cannot know which trade-off matters most in your product unless you provide that context. In this situation, it is similar to asking a fast and confident intern to guess how you would design the feature.</p><p>So instead of asking it to decide for you, there are two useful ways to work with it:</p><p><strong>First: you decide and the agent implements.</strong> You define the responsibility, the boundary and the shape of the solution. Then you give the agent a clear task: &quot;Use a strategy here, keep the existing Handler interface and do not add new abstractions unless they are needed.&quot; At that point, the agent can be very effective.</p><p><strong>Second: you ask, it shows options and you decide.</strong> Perhaps you are not sure whether a problem needs State or Strategy pattern. Ask the agent to show both approaches. Ask what the call site looks like and what changes when a fourth case is added. It can help you explore faster, but the final decision stays with you.</p><p>The less effective approach is to ask the agent to make the decision itself. That is not really delegation, it is skipping the hard part and hoping the generated code happens to match the system you have in mind.</p><h3>Refactoring is a process not a spell</h3><p>Another common expectation is that technical debt can disappear in one request: you ask for a refactor, a beautiful new module appears and the problem is solved.</p><p>In practice, refactoring is a process. You write new code, connect it to the old code that is already running in production, run the app, discover an unexpected behaviour, fix it and run the tests again. Then you find that the fix affected another area. This loop continues until the new implementation replaces the old one without changing the expected behaviour.</p><p>An agent is very good at some parts of this process: repetitive edits across many files, the first version of a module, renames, and other mechanical work.</p><p>But the loop still needs a destination. Someone needs to know what &quot;done&quot; means, what should remain unchanged and which compromises are acceptable. An agent does not reliably keep all of this context through a long sequence of tasks. If you leave it alone for too many iterations, it can drift toward a solution that looks fine locally but no longer matches the original goal.</p><p>That is why it helps to keep the work focused and review it regularly. In practice, I repeatedly remind the agent about three things:</p><p>- <strong>The destination: </strong>where the design should end up.<br>- <strong>The rules:</strong> existing libraries, conventions, helpers, and folder boundaries.<br>- <strong>The taste decision:</strong> when a working but over-engineered solution should become a simpler one.</p><p>This does not fit into one prompt that you can send and forget. It is an ongoing conversation. In many ways, it is close to pair programming.</p><h3>Pair programming without taking a teammate away</h3><p>Extreme Programming introduced pair programming: two developers work on one task, with one person driving and the other navigating. The driver handles the mechanics; the navigator thinks ahead, checks the design and catches mistakes before they spread through the codebase.</p><p>It is a useful practice but it is expensive. It requires two people to work on one task, so it is often the first thing teams drop when deadlines become tight.</p><p>An AI agent changes part of that equation. It is always available and can handle the mechanical work quickly. It can explain unfamiliar code, produce diagrams, prepare a first implementation and apply repetitive changes.</p><p>However, the roles are different. With an agent, the human should be the navigator. You hold the design, the product context and the destination. The agent is the driver: quick, tireless and capable of implementing a lot of code very fast.</p><p>This can be a productive form of pairing but only when the human stays responsible for direction and judgment.</p><h3>A real example: a feature that worked but should not have stayed that way</h3><p>Let me make this more concrete with an example from my experience.</p><p>We had a core feature responsible for the app&#39;s main data. At first, it was simple enough. Then the requirements grew, as they usually do. The data became more complex, new rules appeared and several sources of truth were added.</p><p>The agent handled the changes. To be fair, the feature worked. It adapted the app to the new requirements and met the expected behavior. If the only question was &quot;Does it run?&quot; the answer was yes.</p><p>But the code became difficult to maintain and understand. It was also expensive to work with afterward because every future agent task needed more context just to read the existing implementation and change it safely.</p><p>That is the state we can end up in when we optimize only for &quot;make it work&quot;. The feature runs but the code becomes a liability.</p><p>Here is the approach I used to fix it.</p><h4>First, understand the current implementation</h4><p>Do not start by changing code. First, understand what already exists.</p><p>This is an area where agents are especially helpful. I asked the agent to create an as-is sequence diagram for the relevant flow. Then I used the diagram as a starting point for questions: What calls this method? Why does this path exist? What happens if this value changes? When several sources disagree, which one wins?</p><p>Understanding existing code is not a one-shot task, it is a conversation. The agent can help you read the code much faster but you still need to validate its explanation against the codebase.</p><p>This was roughly the situation we had:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8Q7ABbzfpn1Q5ShpVJlKQ.png" /><figcaption>as is sequence diagram (not a real one, just an example)</figcaption></figure><p>The diagram made the debt visible. Once you can see the flow, it is much easier to discuss what should change and what should remain.</p><h4>Second, add a safety net</h4><p>Before changing the implementation, I added more unit tests that described the current behavior, including the parts that were not very nice.</p><p>You need a safety net before refactoring. Without tests, you are not really refactoring; you are rewriting and hoping that the behavior stays the same. Tests let you know when a small structural change accidentally changed an important rule.</p><h4>Third, design the target state</h4><p>Only after understanding the current code and protecting its behaviour, you decide what the target design should be.</p><p>This is the step I would not give to the agent. I decided where reconciliation belonged, which source should be authoritative and how the remaining sources should defer to it. Then I created a target diagram:</p><figure><img alt="to be sequence diagram (not a real one, just an example)" src="https://cdn-images-1.medium.com/max/1024/1*SAb7gvbJ1X7-tjqYx6PeFw.png" /><figcaption>to be sequence diagram (not a real one, just an example)</figcaption></figure><p>Mermaid or PlantUML is useful here for more than documentation. A diagram gives both you and the agent a shared description of the intended system. When an implementation starts to drift, you can compare it with the diagram instead of trying to resolve the difference through long prompts.</p><h4>Fourth, refactor toward the target in small steps</h4><p>At this stage, the agent can do a lot of valuable work. It implements the changes while you keep the work aligned with the target design. When it suggests an unnecessary abstraction, you can return to the diagram. When it forgets that reconciliation now belongs in one place, you can correct the direction immediately.</p><p>Keep the changes small and keep the tests green. If something fails, stop and understand why before continuing. The final result should be not only working code but code that reflects a design you can explain and maintain.</p><p>The agent did a large amount of implementation work in this refactor. But it did not make the main decisions. That was the important part.</p><h3>The thinking did not disappear</h3><p>There are two common ideas around AI-assisted development: that AI will write all the code for us, or that we only need to learn how to write better prompts. Both miss the same point.</p><p>AI did not remove the difficult part of software development. It made typing and repetitive implementation much cheaper. The difficult part is still understanding the existing system, deciding what to build and keeping the work moving toward the right destination through many small changes.</p><p>You can do this work up front through a specification, a diagram or a clearly stated decision. Or you can pay for it later through confusing code, repeated corrections, more tokens and a future refactor that takes longer than it should.</p><p>The tool is useful. It can be a fast, tireless pairing partner. But it needs direction.</p><p>&quot;Make it good&quot; is not a prompt. It is a wish. The real skill is learning to navigate the work yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd96f9dcea9" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-hardest-part-of-ai-assisted-coding-is-still-thinking-0bd96f9dcea9">The Hardest Part of AI-Assisted Coding Is Still Thinking</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking and Fixing Flutter App Bottlenecks Using Firebase Tools]]></title>
            <link>https://itnext.io/tracking-and-fixing-flutter-app-bottlenecks-using-firebase-tools-e7ae79a9438c?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7ae79a9438c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase-performance]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 16:18:50 GMT</pubDate>
            <atom:updated>2024-10-09T16:18:50.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IPxskKbGI5sTpy2J" /><figcaption>Photo by <a href="https://unsplash.com/@grayomm?utm_source=medium&amp;utm_medium=referral">grayom</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my <a href="https://medium.com/itnext/unlocking-the-power-of-observability-in-your-flutter-app-9525ee873953">previous article</a>, I covered how to use New Relic to enhance the observability of mobile applications. While New Relic offers a robust set of tools for performance monitoring, in this article, we will focus on Firebase Performance and how it can be used to tackle similar tasks.</p><p>Firebase Performance offers a free, comprehensive solution for tracking app performance. As part of the Firebase suite, it provides seamless integration with other Firebase services like Crashlytics, making it easier to manage all performance and crash data in one place. This not only simplifies access but also streamlines team collaboration without the need to manage multiple platforms.</p><p>Below, I will dive into the key features of Firebase Performance for Flutter applications and demonstrate how it can be a viable alternative to New Relic for monitoring app performance.</p><h3>Integrating Firebase Performance in a Flutter App</h3><p>Integrating Firebase Performance into your Flutter application is a straightforward process, especially if you have already set up Firebase. If you haven’t configured Firebase yet, you can refer to the documentation for detailed guidance on setting it up for Flutter projects.</p><p>Once Firebase is configured, you simply need to add the following dependency to your pubspec.yaml file:</p><pre>dependencies:<br>  firebase_performance: ^0.10.0+8</pre><p>Next, enable performance collection by calling FirebasePerformance.instance.setPerformanceCollectionEnabled(true) in your main.dart file.</p><p>After completing these steps, you are ready to trace your network requests and custom events, unlocking the full potential of Firebase Performance for monitoring your application.</p><h3>Monitoring Automatic Performance Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMoxeUHpcK5As_7eOXssmA.png" /></figure><p>Firebase Performance automatically collects a variety of metrics that can be invaluable for developers, such as network traffic, app startup time, and time spent in the background and foreground. Additionally, it tracks screen rendering, providing insights into slow rendering events (those taking longer than 16ms) and freezes (that taking longer than 700ms).</p><p>While these features are highly useful, there are some <strong>limitations</strong> to consider when using Firebase Performance with Flutter applications.</p><p><strong>Firstly</strong>, the app startup time metric only measures the native part of the application, meaning that it does not accurately capture the full startup time, especially the loading of the Flutter portion. <br><strong>Secondly</strong>, the screen rendering metrics also apply solely to native components. While knowing how quickly your main Activity or ViewController loads can be helpful, it’s less relevant for Flutter developers who are more concerned with the performance of Flutter screens.</p><p>Unfortunately, as of now, tracking the rendering performance of Flutter screens is not supported. However, further in this article, I will explore how we can gather similar performance data specific to Flutter screens.</p><h3>Network Request Monitoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPSbQ9b0OlbTJceFPV-lJg.png" /></figure><p>Although network traffic is not automatically tracked by Firebase Performance when using dio, adding this functionality is straightforward. You can either write your own interceptor or use an existing one from <a href="https://pub.dev/">pub.dev</a>. Additionally, if you have a custom wrapper around dio, you can easily integrate request tracing into your existing architecture.</p><p>Assuming you have a wrapper and all network calls are made through the request method of dio, the implementation might look as follows:</p><pre>class DioWrapper {<br>  DioWrapper(this._dio);<br><br>  final Dio _dio;<br><br>  Future&lt;Response&gt; request(String path, {required RequestOptions options}) async {<br>    final HttpMetric metric = FirebasePerformance.instance.newHttpMetric(<br>      options.uri.toString(),<br>      HttpMethod.Get, // Set the right HTTP method<br>    );<br><br>    metric.start();<br><br>    try {<br>      final response = await _dio.request(path, options: options);<br><br>      metric<br>        ..httpResponseCode = response.statusCode<br>      /** <br>        ..requestPayloadSize = requestSize<br>        ..responsePayloadSize = responseSize<br>        ..responseContentType = contentType;<br>      */<br><br>      return response;<br>    } catch (e) {<br>      rethrow;<br>    } finally {<br>      metric.stop();<br>    }<br>  }<br>}</pre><p>This implementation closely mirrors what was done with New Relic. In this case, Firebase Performance can effectively replace New Relic for network request tracing, with minimal functionality lost. The primary drawback is that you won’t have access to New Relic’s advanced features, such as custom dashboards and the ability to filter traffic by user.</p><p>If those features are critical to your workflow, it’s important to evaluate how you’ve used New Relic previously and consider whether Firebase Performance meets your needs. Based on this analysis, you can make an informed decision on whether to stick with Firebase or look for a more comprehensive solution.</p><h3>Using Custom Traces and Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed0oKw6MUH1oAkR8aRqudQ.png" /></figure><p>In my opinion, this is one of the most valuable features of Firebase Performance. Identifying bottlenecks in your code isn’t always straightforward, especially when working on high-end devices, which may mask performance issues. However, Firebase custom traces allow you to track how long specific operations take on actual user devices, offering insights into real-world performance. Creating a trace is similar to how we create an HttpMetric.</p><p>Here’s an example of using a custom trace to monitor the performance of a time-consuming operation:</p><pre>import &#39;package:firebase_performance/firebase_performance.dart&#39;;<br><br>void performHeavyOperation() async {<br>  final trace = FirebasePerformance.instance.newTrace(&quot;heavy_operation_trace&quot;);<br>  await trace.start();<br><br>  await Future.delayed(Duration(seconds: 3));<br><br>  await trace.stop();<br>}</pre><p>This allows you to capture how long the operation takes on different devices. When these traces are collected across your user base, you can see how much time it takes on average or for specific users, giving you insights into potential performance issues.</p><h4>How can custom metrics help?</h4><p>Consider a scenario where you are handling a massive JSON file for localization (why not?). You retrieve it from the backend, parse it, and then use the localized strings in the app. The parsing process likely occurs on the UI thread, which can cause frame drops or even give users the impression that the app has frozen. In this case, it’s essential to track how long the parsing process takes and monitor any changes in this duration over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uplnZ-VvsDzRitAUUkVAxg.png" /></figure><p>Custom traces allow you to measure the parsing time, so you can detect whether this operation is becoming a performance bottleneck. Here’s an example:</p><pre>void parseLargeJson(String jsonString) {<br>  final trace = FirebasePerformance.instance.newTrace(&quot;parse_localization_json&quot;);<br><br>  race.start();<br>  final parsedJson = jsonDecode(jsonString);<br>  trace parseTrace.stop();<br>}</pre><p>By using Firebase Performance’s custom traces, you can monitor and improve performance-critical sections of your code, ensuring that operations run efficiently across a wide range of devices, improving the overall user experience.</p><h3>Detecting Dropped Frames and Diagnosing Freezes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcJvgTRefGDmf4jkbQ2M5w.png" /></figure><p>As mentioned earlier, Firebase provides native apps with the ability to detect freezes and dropped frames, but unfortunately, this functionality isn’t directly available for Flutter applications. It would be beneficial to have such a feature for Flutter apps as well. While it won’t be as polished as the native implementation, we can still create something useful.</p><p>Flutter offers a way to access frame rendering information not only through DevTools, but also by adding a callback that provides detailed frame timing information:</p><pre>SchedulerBinding.instance.addTimingsCallback((timings) {<br>  for (final timing in timings) {<br>    print(&#39;[${timing.frameNumber}] Build took ${timing.buildDuration.inMilliseconds}ms, Raster took ${timing.rasterDuration.inMilliseconds}ms&#39;);<br>  }<br>});</pre><p>The callback will provide a list of timing objects, from which you can access timing.buildDuration and timing.rasterDuration. If either of these stages takes longer than 16ms (for a 60Hz display), you have a janky frame.</p><p>For example, as shown in the screenshot below from DevTools, frames 25 and 26 exceed the 16ms threshold, and you’ll see the same information reflected in the logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CaBy5U0bd3niXGJ37TjEbQ.png" /></figure><pre>I/flutter (10272): [21] Build took 0ms, Raster took 17ms<br>I/flutter (10272): [22] Build took 0ms, Raster took 21ms<br>I/flutter (10272): [23] Build took 0ms, Raster took 16ms<br>I/flutter (10272): [24] Build took 0ms, Raster took 10ms<br>I/flutter (10272): [25] Build took 1ms, Raster took 24ms<br>I/flutter (10272): [26] Build took 3ms, Raster took 33ms</pre><p>Having detailed rendering information enables us to analyze performance and address weak points that may be affecting the app’s responsiveness. To tackle this, we can leverage the capabilities of both Firebase Performance and Firebase Crashlytics. By combining these tools, we can not only track rendering issues but also gain valuable context to make informed improvements.</p><h4>Logging to Firebase Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQzVR8di6RQ_pyRmhRPoBg.png" /></figure><p><strong>The first</strong> option is to create a custom trace in Firebase Performance to log this information. However, there’s a challenge: Firebase Performance does not allow you to create a trace with a specified start and end time.</p><p>We could implement a workaround like this:</p><pre>static void _logWithTime(Duration d, String name) async {<br>  final trace = FirebasePerformance.instance.newTrace(name);<br>  trace.start();<br>  await Future.delayed(d);<br>  trace.stop();<br>}</pre><p>But even this approach has limitations. There’s no guarantee that trace.stop() will be called exactly after Duration d—for example, if a large JSON file is being parsed at that moment. Even if we accept this inaccuracy, another issue arises: Firebase Performance won&#39;t provide additional information about the trace, such as which screen the user was on or what actions led up to the janky frame. This leaves us with minimal insight—just that a freeze occurred somewhere in the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ur43LkhMcwyVpPCF0wLzMQ.png" /></figure><p><strong>The second one</strong> is to create a custom trace in Firebase Performance to log this information. You could even save <strong>all rendering data</strong>, not just those that exceed 16ms. This approach would allow you to gather comprehensive insights into how long rendering takes on users’ devices, helping you analyze the distribution and determine the percentage of frames that take less than 16ms. As a general performance indicator, this would be a valuable metric for understanding overall app responsiveness.</p><p>For example, you might log the following data to Firebase Performance:</p><pre>for (final timing in timings) {<br>    final trace = AppTracing.createTrace(&quot;frame_rendering&quot;);<br>    await trace.start();<br>    trace.setMetric(&quot;build_duration&quot;, timing.buildDuration.inMilliseconds);<br>    trace.setMetric(&quot;raster_duration&quot;, timing.rasterDuration.inMilliseconds);<br>    await trace.stop();<br>}</pre><p>As seen in the screenshot above, the 90th percentile of frames shows that rasterization takes only 3ms, while building takes 9ms for the same percentile. This provides a convenient way to monitor the overall performance of your application and helps in identifying potential areas for optimization.</p><h4>Logging to Firebase Crashlytics</h4><p>What if we log this data in Firebase Crashlytics instead? Since Crashlytics likely already logs analytics events, screen transitions, and other context, it could be easier to pinpoint the problematic area. Additionally, logging non-fatal errors in Crashlytics won’t affect your crash-free rate.</p><p>Here’s how we log that data:</p><pre>for (final timing in timings) {<br>  if (timing.totalSpan.inMilliseconds &gt; 16) {<br>      FirebaseCrashlytics.instance.recordError(<br>        Exception(&#39;JankFrame&#39;),<br>        null,<br>        information: [timing.toString()],<br>        printDetails: true,<br>        fatal: false,<br>      );<br>  }<br>}</pre><p>This solution logs janky frames directly into Crashlytics as non-fatal errors. Because Crashlytics already collects user sessions and screen transition events, you can cross-reference this data to identify what led to the performance issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB1UnGU9D_8cWTAZlA621Q.png" /></figure><p>For instance, after adding logging to Crashlytics, you might find that building MigraineDetailsPag takes too long. This information allows you to take actionable steps to enhance user experience (UX), rather than simply knowing there are rendering issues in the app.</p><h3>Conclusion</h3><p>In summary, leveraging Firebase Performance in conjunction with Crashlytics for monitoring your Flutter application’s performance can significantly enhance your ability to identify and address bottlenecks. With insights into user behavior and performance patterns, you can iteratively improve your app’s responsiveness while maintaining high standards of user satisfaction.</p><p>As you continue to optimize your Flutter applications, consider incorporating Firebase Performance into your performance monitoring strategy. This not only helps you track essential metrics but also empowers you to create a smoother and more enjoyable experience for your users.</p><p>Don’t forget to clap, comment, and <strong>share</strong> if you found this helpful! Let’s spread the knowledge together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7ae79a9438c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/tracking-and-fixing-flutter-app-bottlenecks-using-firebase-tools-e7ae79a9438c">Tracking and Fixing Flutter App Bottlenecks Using Firebase Tools</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Observability in Your Flutter App]]></title>
            <link>https://itnext.io/unlocking-the-power-of-observability-in-your-flutter-app-9525ee873953?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9525ee873953</guid>
            <category><![CDATA[new-relic]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[crashlytics]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 08:51:35 GMT</pubDate>
            <atom:updated>2024-06-24T08:51:35.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-uo7GPq98diGC1FVa0A3g.png" /></figure><p>In the fast-paced world of Flutter development, ensuring your app works as expected is crucial. But how do you keep track of everything happening inside your app? The answer lies in observability. With tools like Crashlytics and NewRelic, you can monitor, debug, and optimize your Flutter app with ease. This article delves into our experience using these services in our startup, <a href="https://beauty.versetech.app/">Beauterra</a>, a platform designed to empower independent beauty artists. We’ll explore how these tools have transformed our development process and enhanced our app’s performance.</p><h3>Crashlytics: Your First Line of Defense Against Crashes</h3><p>Firebase Crashlytics is a powerful crash reporting tool that helps you track, prioritize, and fix stability issues. It provides detailed insights into the nature of crashes, helping you understand their root causes.</p><h4><strong>Key Features of Crashlytics</strong></h4><p>Crashlytics offers real-time crash reports, allowing you to quickly identify and address issues as they occur. With comprehensive stack traces, you can see exactly where and why a crash occurred. Understanding how many users are affected by a crash helps you prioritize fixes based on impact.</p><h4>Maximizing Crashlytics for Better Results</h4><p><strong>Use Keys:</strong> Add important data such as user IDs and FCM tokens. This way, you can check why a user experienced an issue and send a push notification once it’s fixed. Include any other relevant data that can aid in troubleshooting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Sq3qYedzg8Pj8Q_0QcyRg.png" /><figcaption>Added keys for the crash</figcaption></figure><p><strong>Use Logs:</strong> Sometimes, a stack trace alone isn’t enough to understand a problem. Logs can help you track view states and other actions leading to non-fatal events. For instance, if an action button is incorrectly shown, logs can reveal whether the user agreed to certain conditions, leading to a non-fatal event. Screen view events are particularly useful, allowing you to see the sequence of actions before a crash occurs. Additionally, all tracked Google Analytics events are visible in Crashlytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpNQnKfJp4-4M33ag7PDOw.png" /><figcaption>Sequence of actions before a crash occurs</figcaption></figure><h3>NewRelic: Beyond Crash Reporting</h3><p>While Crashlytics excels at tracking crashes, NewRelic takes observability a step further. It provides a comprehensive suite of tools for monitoring performance, tracing, and analytics.</p><h4>Key Features of NewRelic</h4><p>NewRelic collects HTTP traffic data including status codes, request URLs, and request times, enabling you to detect user-specific API issues easily. With performance monitoring, you can track key metrics like response times, throughput, and error rates. Distributed tracing helps you understand how different parts of your app interact, identifying bottlenecks. Custom dashboards and alerts allow you to visualize your data and set up notifications for specific conditions.</p><h4>Maximizing NewRelic for Better Results</h4><p>We implemented a custom event system to track parts of the app that fail. These events, named starting with fail_to, provide detailed context. For example, our chat feature relies on both Firestore and backend data. When user data fails to load, we track an event like fail_to_get_public_user, including user IDs and relevant parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLHuWBl_DQszuzzs9e5IUQ.png" /><figcaption>All happened issues in the time period</figcaption></figure><p>To enhance tracking, we attach user IDs to NewRelic events once the user logs in, allowing us to identify who encountered specific issues. Including exceptions in the event parameters helps us understand what went wrong. Our dashboard shows events in near real-time and can filter by event name or user ID, making it easy to diagnose issues and trace problems back to the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPpSglPEGTPmB3fbAyAEhA.png" /><figcaption>Filtered dashboard by the user ID</figcaption></figure><h4>Querying Critical Events for Insights</h4><p>To effectively monitor and diagnose critical issues in your app, you can use NewRelic’s querying capabilities to create meaningful visualizations and dashboards. We have a custom event type called Critical. We use it to track all events, expect HTTP ones. Here are some queries we use to build the diagrams and table above:</p><h4>Count of Critical Events by Name</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ajfk96hIZPBuqj1uMQXIog.png" /></figure><p>This query counts the occurrences of critical events categorized by their names over the last 12 hours. It helps in identifying which types of issues are most prevalent in the app.</p><pre>SELECT count(name) FROM Critical FACET name SINCE 12 hours AGO</pre><p><strong>Count of Critical Events by User ID (Issues Count)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umN069bCB8DIereEuPu44A.png" /></figure><p>This query aggregates critical events based on user IDs, providing insights into which users are experiencing the most issues within the specified timeframe. It helps prioritize support efforts or identify patterns affecting specific user segments.</p><pre>SELECT count(userId) as Issues FROM Critical FACET userId SINCE 12 hours AGO</pre><p><strong>Recent Critical Events Details</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fq7yo9C0K8ZJbwlN85QDaw.png" /></figure><p>This query retrieves detailed information about the most recent critical events, including timestamp, app version, operating system, user ID, event name, and the cause of the issue. Limiting to the latest 20 events helps in quickly assessing recent issues and their impact.</p><pre>SELECT timestamp, appVersion, osName as Platform, userId, name, cause <br>FROM Critical <br>ORDER BY timestamp DESC <br>LIMIT 20 <br>SINCE 12 HOURS AGO</pre><h4>Case Study</h4><p>One of our users reported that the app wasn’t working. Minutes later, we discovered that this user had no internet connection, which was the root cause. While we should have shown an error screen for connectivity issues, NewRelic helped us quickly diagnose the problem, saving valuable time.</p><h3>Addressing Potential Concerns</h3><h4>Mitigating Overhead</h4><p>Both Crashlytics and NewRelic are designed to minimize impact on your app’s performance. By focusing on key metrics, you can gain valuable insights without significant overhead. Remember, it’s more important to know when something doesn’t work than to confirm that it does. Use tools like Google Analytics or Amplitude for general feature tracking.</p><h4>Balancing Complexity</h4><p>Integrating observability tools does add some complexity to your development process. However, the long-term benefits of faster issue resolution and improved app performance outweigh the initial setup effort.</p><h3>Embrace Observability for a Better Flutter App</h3><p>Incorporating observability into your Flutter app development process is a game-changer. With tools like Crashlytics and NewRelic, you gain the visibility needed to quickly identify and resolve issues, optimize performance, and ensure a seamless user experience. By investing in observability, you’re not just fixing problems faster — you’re building a more resilient and high-performing app.</p><p>Remember, the chances of encountering bugs and crashes are high, but with robust observability, your chances of resolving them swiftly are even higher. Embrace these tools and take your Flutter development to the next level.</p><p>Don’t forget to clap, comment, and <strong>share</strong> if you found this helpful! Let’s spread the knowledge together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9525ee873953" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/unlocking-the-power-of-observability-in-your-flutter-app-9525ee873953">Unlocking the Power of Observability in Your Flutter App</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Half Circle Progress Bar]]></title>
            <link>https://itnext.io/how-to-create-a-half-circle-progress-bar-10d22e2d4b29?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d22e2d4b29</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[custompainter]]></category>
            <category><![CDATA[custom-widget]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Sun, 16 Oct 2022 20:01:58 GMT</pubDate>
            <atom:updated>2022-10-18T15:18:34.142Z</atom:updated>
            <content:encoded><![CDATA[<p>I bet you all had situations when a designer made a cool-looking UI and you just thought “cool, but how to implement this”. The same happened to me when a saw this progress bar in Figma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*75IcrkqXF0hdboTG0AJGRg.gif" /><figcaption>How it looks like</figcaption></figure><p>Good thing is that in Flutter it’s pretty easy to create custom views and they will look awesome on every platform, but sometimes you just need to remember all these things that you have learned in geometric, and math classes. <em>Yeah, we don’t always change the button’s color as someone thinks :)</em></p><h3>A little bit of geometry</h3><p>Let’s think what we have to make to implement the progress bar. Firstly, we have to find out a way to understand how many dots should be on the half-circle. Secondly, how to place these dots on it.</p><h4>Calculating the number of dots</h4><p>Let’s start simple, what if we have a straight line and we need to calculate how many points it can fit. The answer is that you take the length of the line, divide it by the diameter of the dot and add padding between them. And that’s done.</p><p>We do the same, but with a circle. If you know the radius of the circle, we can find its length. The formula is 2 * pi * r, but we need only half of it, so for us, the formula will be:</p><pre>lineLength = pi * r</pre><p>Finally, we know the size (radius or diameter) of the dots and the spacing between them, so we can simply divide the line’s length by the size of the dots with spacing. So we have a formula like this:</p><pre>dotsNumber = floor(lineLength / (dotDiameter + dotsSpacing))</pre><p>We use floor because we can’t draw, say, half of the dot.</p><h4>Placing dots on the circle</h4><p>If we had a line, that would be easy to place the dots on it. We would start from 0 and would add dotDiameter + dotsSpacing after the dots have been drawn.</p><p>Unfortunately, in our case, we can’t do it like that. To place dots on the circle we will use Polar Coordinates and will specify two coordinates:<br>1. how far away is the dot from the circle’s center (<strong>r)</strong>,<br>2. dot’s angle <strong><em>(θ)</em></strong>.</p><p>Having these coordinated we can easily convert them to Cartesian coordinates and draw afterward. The formulas are:</p><pre>x = circleRadius * sin(dotAngle) + circleCenterX<br>y = circleRadius * cos(dotAngle) + circleCenterY</pre><h3>Implementation</h3><p>We have everything to start implementing the progress bar. We will use a CustomPainter class to draw the view on the canvas.</p><h4>The painters</h4><p>Let’s add all arguments that we need and implement methods the CustomPainter requires, but the paint method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3255db2d57f75352dfc68aa007cba3e2/href">https://medium.com/media/3255db2d57f75352dfc68aa007cba3e2/href</a></iframe><p>There we have arguments to customize the progress bar, like the dot’s colors, spacing between dots and layers, and radius of the first (inner) circle. Also, we create the painters, so we won’t instantiate them every time in the painting method.</p><p>Don’t forget to implement shouldRepaint method, so the view gets repainted once one of the arguments is changed.</p><h4>Draw first circle</h4><p>Let’s implement the paint method that draws a circle with dots.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a776b9d677c52dac5012277e955ec13e/href">https://medium.com/media/a776b9d677c52dac5012277e955ec13e/href</a></iframe><p>Here we get the center of the circle, calculating how many dots will be on the circle and the angle between them.</p><p>The important thing here is that we start drawing the dots from 270 angles (_startAngle) because we want the first dot to be in the bottom left corner and moving clockwise.</p><p>Also, have a look at how we calculate how many dots should have different (progress) colors.</p><h4>Draw more layers</h4><p>The last thing is to add more layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/797c44921e61b0fa5e57b86722d55429/href">https://medium.com/media/797c44921e61b0fa5e57b86722d55429/href</a></iframe><p>A for-loop has been added and for every tick, we just increase the circle’s radius by adding the dot’s diameter and spacing between layers.</p><h3>Wrap it</h3><p>You can use your CustomPainter by wrapping it with the CustomPaint widget, but I think that is not user-friendly. So let’s wrap the painter with our widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c18745e0521083e3ce2d452fc70d466/href">https://medium.com/media/4c18745e0521083e3ce2d452fc70d466/href</a></iframe><p>Here is the widget that encapsulates some things about the painter and adds default values for the required arguments. The important thing here is that we add size for the CustomPaint so that Painter knows the size of the canvas and the widget can be correctly positioned, for example, in a Stack widget.</p><p>Also, ClipRect is added to cut everything that is out of the parent widget. That happens when a parent widget is smaller than the size needed to draw the progress bar.</p><p>—</p><p>That’s all :) Feel free to add any comments or suggestions and share, clap if you found it helpful!</p><p>Here is the link to the repository — <a href="https://github.com/ValeryPonomarenko/flutter-half-circle-progress-bar">https://github.com/ValeryPonomarenko/flutter-half-circle-progress-bar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d22e2d4b29" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-create-a-half-circle-progress-bar-10d22e2d4b29">How to Create a Half Circle Progress Bar</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation in Multi-Module Projects]]></title>
            <link>https://proandroiddev.com/navigation-in-multi-module-projects-9a5c53ad219?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5c53ad219</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[multi-module-project]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 05:37:40 GMT</pubDate>
            <atom:updated>2019-03-11T09:00:04.521Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlWn4ojvmK8k8-tLHWbCCw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@vividcafe?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Aleksejs Bergmanis</a> from <a href="https://www.pexels.com/photo/aerial-photo-of-buildings-and-roads-681335/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Navigation in developing Android apps is quite important and you should think twice what library suits (or your own solution) most and how it will be convenient to use when the app becomes bigger. Also, it might be good to think about how easy it will be to change your implementation to another one.</p><p>Before we will start, let me tell a story. Let&#39;s call it like this &quot;How we made project modular and why I hated our navigation&quot;.</p><p>We had a single module project and everything worked fine except building time, that is because we used Dagger and it took too long to generate a single component. So we decided to separate the project into modules by features, for example, a login feature, a help feature and etc.</p><p>We had a lot of difficulties because we had to move network logic into its own Gradle module, domain login into its module and also we had issues with the navigation.</p><p>In our implementation, we had a router that knew about every Fragment and it was responsible for transitions between them. Unfortunately, every Fragment knew that there was the router and knew about other Fragments, because the Fragment said to the router what Fragment should be opened or the Fragment was waiting for the results from another Fragment. These things ruined the idea of making independent feature modules.</p><p>Therefore, I have been thinking how to make it better, how to break these connections between Fragments, how to get rid of knowledge that there is some router. In this article, I will show what I have made.</p><h3>What we will do</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*sQPQIhakVlhq--AvqnUeNg.gif" /><figcaption>Application</figcaption></figure><p>The application will be super simple but it will be modular. There will be one application module and three feature modules:</p><ul><li><strong>App</strong> module — this module knows everything about the app and there we will implement our navigation. We will use the Navigation Component from JetPack.</li><li><strong>Questions</strong> module — this module is responsible for the questions feature. The module knows nothing about the <strong>App</strong> module or any other module. There will be a QuestionsFragment and a QuestionsNavigation interface.</li><li><strong>Question</strong> module — there will be a question feature. As the previous module, it does not know about other modules. That module will contain a QuestionFragment and a QuestionNavigation interface.</li><li><strong>Result</strong> module — this is a result feature. Also, it completely independent module. There will be a RightAnswerFragment with RightAnswerNavigation interface and there will be a WrongAnswerFragment with WrongAnswerNavigation interface.</li></ul><p>The source code for the app can be found here:</p><p><a href="https://github.com/ValeryPonomarenko/modular-navigation">ValeryPonomarenko/modular-navigation</a></p><h3>Implementation</h3><p>In this article, I will use <strong>ComponentsManager</strong> library to get the feature&#39;s navigation. In a real project, I will provide feature&#39;s navigation by <strong>Dagger</strong> but for this small project it is not necessary. Also, the <strong>ComponentManager</strong> library helps you to use <strong>Dagger</strong> in multi-module projects.</p><p><a href="https://github.com/ValeryPonomarenko/ComponentsManager">ValeryPonomarenko/ComponentsManager</a></p><p>Are you ready? Let&#39;s go!</p><h4>Questions Module</h4><p>Create an Android module and call it <strong>questions</strong>. After that make sure that Kotlin is configured in the module and the <strong>ConstraintLayout</strong> and the <strong>ComponentsManager</strong> are added as dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407d63534115b46415beee411e27698f/href">https://medium.com/media/407d63534115b46415beee411e27698f/href</a></iframe><p>Instead of using Route or Navigator in the Fragment, we will create an interface QuestionsNavigation that defines the needed transitions. Thus for the Fragment, it does not matter how those transitions will be implemented, it just needs that interface and relies on when the method is called, the needed screen will be open.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e4e067aef201ccf2aa5283c0e9bf95b/href">https://medium.com/media/1e4e067aef201ccf2aa5283c0e9bf95b/href</a></iframe><p>To open a screen with a question, we just call the openQuestion(questionId: Long) method and that is it. We do not care how the screen will be opened, we do not even care whether it is Fragment or Activity or something else.</p><p>Here is the QuestionsFragment and its <a href="https://github.com/ValeryPonomarenko/modular-navigation/blob/master/questions/src/main/res/layout/fragment_questions.xml">layout</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2e5aaa2518436b98d918c96a60239a/href">https://medium.com/media/0c2e5aaa2518436b98d918c96a60239a/href</a></iframe><h4>Question Module</h4><p>Firstly, create an Android library module and call it <strong>question</strong>. The module&#39;s build.gradle must contain the same dependencies as the question module&#39;s build.gradle file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407d63534115b46415beee411e27698f/href">https://medium.com/media/407d63534115b46415beee411e27698f/href</a></iframe><p>After that we create an interface that defines module&#39;s navigation. The navigation idea in other modules will be the same as in the previous one.</p><p>From the QuestionFragment user can open a wrong answer screen or a right answer screen so the interface will have two methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ec88b45c1c866b5a8fc40ad7a6dda8/href">https://medium.com/media/11ec88b45c1c866b5a8fc40ad7a6dda8/href</a></iframe><p>The last thing is fragment. For this fragment, we will add a companion method that returns a Bundle so we will be able to pass question&#39;s id and use it. The fragment&#39;s <a href="https://github.com/ValeryPonomarenko/modular-navigation/blob/master/question/src/main/res/layout/fragment_question.xml">layout</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b3cf0f1d16c587fbcbd28a194d44e8d/href">https://medium.com/media/0b3cf0f1d16c587fbcbd28a194d44e8d/href</a></iframe><h4>Result Module</h4><p>The final feature module is result module. There will be two fragments that show a right and wrong answer. Create an Android library module and call it <strong>result</strong>, then change the module&#39;s build.gradle so it will have the same dependencies as the previous feature modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407d63534115b46415beee411e27698f/href">https://medium.com/media/407d63534115b46415beee411e27698f/href</a></iframe><p>Let&#39;s start from the right answer fragment. The navigation interface will have one method because the user can open only an all question screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7810ecd209edcf6e2e06a4d2ac7ab6fa/href">https://medium.com/media/7810ecd209edcf6e2e06a4d2ac7ab6fa/href</a></iframe><p>The RightAnswerFragment, its <a href="https://github.com/ValeryPonomarenko/modular-navigation/blob/master/result/src/main/res/layout/fragment_right.xml">layout</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2bc53b644786f4d8503ab0e8f56eed7/href">https://medium.com/media/a2bc53b644786f4d8503ab0e8f56eed7/href</a></iframe><p>As I said earlier, this module has two Fragments, so let&#39;s implement a wrong answer screen.</p><p>In my implementation, from the wrong answer screen user can only go back to the question&#39;s screen and try to answer the question again, so the navigation interface has only one method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bef4e87bce1cc0c72e6318f42e110f1/href">https://medium.com/media/0bef4e87bce1cc0c72e6318f42e110f1/href</a></iframe><p>And the WrongAnswerFragment, its <a href="https://github.com/ValeryPonomarenko/modular-navigation/blob/master/result/src/main/res/layout/fragment_wrong.xml">layout</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6891414d682418606c6c3e763645e93d/href">https://medium.com/media/6891414d682418606c6c3e763645e93d/href</a></iframe><h4>App Module</h4><p>We have made the modules and it is time to connect them and run the app.</p><p>First thing first, we need to edit the app module&#39;s build.gradle. It must have all the created modules and a Navigation Component library with the Components Manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe91a4a6ecb8154a72d52245a139803f/href">https://medium.com/media/fe91a4a6ecb8154a72d52245a139803f/href</a></iframe><p>Before implementation the classes that work with navigation, we have to add the navigation itself. We will use the Navigation Component to built it.</p><p>Create a navigation resource file and call it <strong>nav_graph.xml</strong>. There will be three connections:</p><ul><li>The QuestionsFragment with the QuestionFragment</li><li>The QuestionFragment with the WrongAnswerFragment</li><li>The QuestionFragment with the RightAnwerFragment. This connection has a little difference. If the user in on the RightAnswerFragment and the user presses the back button, he or she will be returned to the QuestionsFragment. How make that happen? Just select the arrow that connects the questionFragment with rightAnswerFragment, then in the drop-down list near the <strong>Pop to </strong>select the questionsFragment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZm7NS26s_-wHNarrV6dWA.png" /><figcaption>Navigation Graph</figcaption></figure><p>Here is the XML representation of the navigation graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7a8cddf2dba03a8ea4bd140963286b/href">https://medium.com/media/fc7a8cddf2dba03a8ea4bd140963286b/href</a></iframe><p>Then, create a Navigator class. Obviously, the class is responsible for making transitions between fragments. It implements all the navigations interfaces from the feature modules, do not forget to add calls of the corresponding actions to open the required screen. Also, the class has methods to bind the navController and unbind it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12331eb16aa260175b6821c3f74daa2f/href">https://medium.com/media/12331eb16aa260175b6821c3f74daa2f/href</a></iframe><p>On the 8th line you can see how I pass question&#39;s id to the QuestionFragment.</p><p>After that, create a NavApplication class. Actually, I had to add this class to make Navigator available to other classes, otherwise, it would be harder to get the navigator in the feature modules. Do not forget to add this class to Manifest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1621aad2fb1fbced47f2667f8236e4a4/href">https://medium.com/media/1621aad2fb1fbced47f2667f8236e4a4/href</a></iframe><p>With the 4th-6th lines, it would be possible to get the implementations of features&#39; navigation interface by calling XInjectionManager.findComponent&lt;QuestionNavigation&gt;().</p><p>The last but not least, change the MainActivity class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e121b3419f860e9bbd4c13903d150034/href">https://medium.com/media/e121b3419f860e9bbd4c13903d150034/href</a></iframe><p>And the activity&#39;s layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d918ec9d1a94638f290aa52c435fc7e/href">https://medium.com/media/9d918ec9d1a94638f290aa52c435fc7e/href</a></iframe><p>That is all, now you can run the app and see how it works.</p><h3>Summary</h3><p>Good job! We have made a navigation system that:</p><ul><li>breaks the connections between fragments in different feature modules,</li><li>can be easily changed,</li><li>is easy to test.</li></ul><p>Thank you for reading! Do not forget to clap 👏, follow and share. Feel free to ask me any questions here or on <a href="https://www.linkedin.com/in/ponomarenkovalery/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5c53ad219" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/navigation-in-multi-module-projects-9a5c53ad219">Navigation in Multi-Module Projects</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test and publish your apps with CircleCI + Fastlane + Firebase Test Lab]]></title>
            <link>https://proandroiddev.com/test-and-publish-your-apps-with-circleci-fastlane-firebase-test-lab-e716c075b99b?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e716c075b99b</guid>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 07:15:23 GMT</pubDate>
            <atom:updated>2018-10-22T13:18:41.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRO3jvES_NCaXSpxzNj--Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@drew_beamer">Drew Beamer</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Have you ever thought how to run UI tests without lots of devices, how to publish the app without visiting the Google Play Console or maybe how to make a “program” that will check your code with lint, then run the unit and the UI tests, and finally, publish the app on Google Play? If so and you did not find a solution, I will show you how it can be done.</p><p>As a CI service, we will use <strong>CircleCI</strong> because they give you 1500 free build minutes per month and also it is possible to build projects that are hosted in the private repositories, but CircleCI only works with GitHub and Bitbucket. For running UI tests we will use <strong>Firebase Test Lab</strong> because they allow you to run up to 15 instrumentation tests per day. <strong>Dropbox</strong> to store the signing key and its credentials. Also, we will use <strong>Fastlane</strong>, because it simplifies some of the processes, like publishing the app on Google Play.</p><h3>Preparation</h3><p>Before we can start implementing the workflow, we need to get the keys. What key do we need? The <strong>Dropbox key</strong> — it will be used for downloading the archive with signing key and its credentials from your Dropbox account. The <strong>Firebase key</strong> — with this key we will be able to run the instrumentation tests in Firebase Test Lab. The final one is the <strong>Google Play key</strong> — this key is going to be used for publishing the app on Google Play.</p><p>Also, we will write two bash scripts. The first one is for downloading the signing data and the second one is for running the instrumentation tests. Actually, they are not so important and you can do everything without them, but in my opinion, with them, the solution will be cleaner.</p><h4>Obtaining the keys</h4><p>How to get the <strong>Firebase</strong> <strong>key</strong>?</p><ol><li>Go to Google Cloud Platform,</li><li>Select the Firebase project,</li><li>Then select the <strong>IAM &amp; Admin &gt; Service accounts</strong> in the left menu,</li><li>Click the <strong>Create Service Account</strong> button,</li><li>Follow the instruction,</li><li>Give an <strong>Editor</strong> role for the service account,</li><li>Save the key as a JSON file and name this file as <strong>gcloud_key.json</strong>.</li></ol><p>How to get the <strong>Google Play</strong> <strong>key</strong>?</p><ol><li>Go to Google Play Console,</li><li>In the left menu select &quot;Settings&quot;,</li><li>Go to API access section,</li><li>Click the <strong>CREATE SERVICE ACCOUNT</strong> button,</li><li>Follow the instruction (it the same as you did to get the Firebase key),</li><li>Give an <strong>Editor</strong> role for the service account,</li><li>Save the key as a JSON file, also name this file as <strong>gplay_key.json</strong>,</li><li>Go back to the Google Play&#39;s Settings page and click <strong>GRAND ACCESS</strong>,</li><li>In the <strong>role</strong> field select <strong>Release Manager</strong>.</li></ol><p>How to get the <strong>Dropbox key</strong>?</p><ol><li>Go to the My apps section in Developers page,</li><li>Create an app,</li><li>Click the <strong>Generate</strong> button in the <strong>OAuth 2</strong> section,</li><li>Save the key somewhere.</li></ol><p><strong>Do not commit</strong> these keys into the repository.</p><h4>Bash scripts</h4><p>Now we will create two bash scripts that will be located in the project. Create a folder in the root of your project and name the folder as <strong>ci</strong>. Then, copy-and-paste the given scripts and do not forget to make them executable (chmod +x filename).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9de5a4cf4d97f11a3910feac36565d6/href">https://medium.com/media/e9de5a4cf4d97f11a3910feac36565d6/href</a></iframe><p>Name this script as <strong>download_ci_data.sh</strong>. This script will download the signing data from your Dropbox account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e552ea8c3156854d64853319400427a0/href">https://medium.com/media/e552ea8c3156854d64853319400427a0/href</a></iframe><p>Name this script as <strong>run_firebase_tests.sh</strong>. This script will upload the APKs and the instrumentation tests will be run. The --async flag means that the script will not wait until the tests will be finished.</p><p><strong>Commit</strong> this folder into the repository.</p><h4>Add variables</h4><p>Before we can add the variables, we must create a project in <strong>CircleCI</strong>.<br>Log in with your Github or Bitbucket account (if you log in with the Github account, you will see the repositories that are hosted in Github, but if you log in with Bitbucket account, you will see the Bitbucket&#39;s repositories). After you were logged in, go to <strong>ADD PROJECT</strong> page and create a project for one of your repositories by clicking the <strong>Set Up Project</strong> button. On the next page, click the <strong>Start building</strong> button. For the first time, your project will not be built, but we will fix it later.</p><p>After the project was created, go to <strong>Settings &gt; Projects</strong> and click on the <strong>gear</strong> button that is located on the right to project’s name. On the next page, go to the <strong>Environment Variables</strong> section.</p><p>Here you need to add 5 variables:</p><ol><li><strong>DROPBOX_KEY </strong>— copy the Dropbox key,</li><li><strong>GCLOUD_SERVICE_KEY </strong>— copy the text that is inside the <strong>gcloud_key.json</strong>,</li><li><strong>GOOGLE_PLAY_KEY </strong>— copy the text that is inside the <strong>gplay_key.json</strong>,</li><li><strong>GOOGLE_PROJECT_ID </strong>— copy the Firebase project id,</li><li><strong>SIGNING_ARCHIVE_NAME </strong>— the name of the archive with the signing key and its credentials.</li></ol><p><strong>Signing config</strong></p><p>The last but not the least, you should add a singing config to the app&#39;s<strong> build.gradle</strong>. We can sign the app via Fastlane, but unfortunately, the key&#39;s credentials will be printed in the log, and from my perspective, it is not safe.</p><p>First thing first, create a file in the root of the project and name it <strong>signing.properties</strong> and add these lines to the file:</p><pre>keyAlias=debug                       <br>keyPassword=debug                       storeFile=../signing.properties                       storePassword=debug</pre><p>Then in the app&#39;s <strong>build.gradle</strong>, read the created file and load its data into the properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0f58c15942a37d884d8ab12aef6369/href">https://medium.com/media/4e0f58c15942a37d884d8ab12aef6369/href</a></iframe><p><strong>Commit </strong>the properties file. We do this file because <strong>signing.properties</strong> is required by Gradle, so without it, the project will not be synced. If you want to sign the app, you will need just to replace this <strong>signinig.properties</strong> file with the correct one.</p><p>Also, generate a signing key and fill the <strong>signing.properties</strong> file with proper credentials. Then create an archive with the key and the <strong>signing.properties</strong> file, additionally, name the archive with the name that you have entered in the <strong>SIGNING_ARCHIVE_NAME </strong>variable. After that, upload the archive into the root of your Dropbox account.</p><h3>Fastlane</h3><p>We need to initialize Fastlane so it will know app&#39;s package, where the key to access Google Play is. To do this step, you will need installed Fastlane on your machine (<a href="https://docs.fastlane.tools/getting-started/android/setup/#installing-fastlane">how to install Fastlane</a>).</p><p>Firstly, open a terminal and go to the project&#39;s folder, then execute this command fastlane init. <br>Then, enter app&#39;s package name, after that, you will be asked to enter the path to the JSON file, enter <strong>gplay_key.json</strong>. <br>After that, the wizard asks whether you need to download metadata from Google Play or not — press <strong>n</strong>, because we do not need this data. <br>After an initialization, you will have a <strong>fastlane</strong> folder and a <strong>Gemfile</strong> in the root of the project. Also, inside the <strong>fastlane</strong> folder, there will be two files inside it: <strong>Appfile</strong> and <strong>Fastfile</strong>. <strong>Commit</strong> all these files into the repository.</p><p>Now we are ready to implement the lanes. There will be 5 lanes that are:</p><ol><li>Running the unit tests,</li><li>Assembling the debug APK,</li><li>Assembling the android test APK,</li><li>Running the instrumentation tests,</li><li>Assembling the release ABB and publishing it on the internal track.</li></ol><p>These lanes must be written in the <strong>Fastfile</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83034a6066cee58544e81cc00a78822f/href">https://medium.com/media/83034a6066cee58544e81cc00a78822f/href</a></iframe><p>The first 3 lanes just run the Gradle tasks.<br>The <strong>instrimentation_tests</strong> task runs the lanes that will assemble needed APKs and after that, runs the <strong>run_firebase_tests.sh</strong>. <br>The last lane runs a Gradle task that will assemble a release ABB and uploads it to Google Play. The lane_context[SharedValues::GRADLE_ABB_OUTPUT_PATH].to_s variable contains path to the ABB. If your app&#39;s path is different from the default one, you will need to enter the right path.</p><h3>CI config</h3><p>Before we continue with the CI&#39;s config file, it would be nice if you could read this <a href="https://circleci.com/docs/2.0/configuration-reference/#section=configuration">page</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73dd6104ecf535350d96ec224c308f3b/href">https://medium.com/media/73dd6104ecf535350d96ec224c308f3b/href</a></iframe><p>This is a config file for CircleCI. At first, read it through and then I will describe each step in details.</p><p>We will use the <strong>circleci/android:api-28-alpha</strong> docker image because it has everything that we need for our building process, like, Java SDK, Android SDK, gcloud, Ruby and so on.</p><p>Also, I add these lines, because I do not feel like writing them in every job.</p><pre>defaults: &amp;defaults<br>  docker:<br>    - image: circleci/android:api-28-alpha<br>  environment:<br>    JVM_OPTS: -Xmx3200m</pre><p>You can add these lines in every job by adding that line &lt;&lt;: *default. If you want to learn more about it, search for the <strong>anchor</strong> in <a href="https://learnxinyminutes.com/docs/yaml/">this article</a>.</p><h4>Run the unit tests</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/438ad8d42a263bbad66fbba7fef2ae60/href">https://medium.com/media/438ad8d42a263bbad66fbba7fef2ae60/href</a></iframe><p>Let&#39;s have a look at the <strong>unit-tests</strong> job. <br>Firstly, the job checkouts the code from the repository, then restores the cache (we will cache the <strong>.gradle</strong> folder to make builds faster), after that, the job installs Fastlane and its dependencies.<br>After the installation, the job is ready to run the unit tests, therefore, it runs the <strong>unit_tests</strong> lane by executing bundle exec fastlane unit_tests.<br>After running the unit tests, the job saves the reports that are located at app/build/reports in artifacts. You can get these files in the build&#39;s page in the <strong>Artifacts</strong> section. <br>Finally, the job saves the <strong>.gradle</strong> folder in the cache.</p><h4>Run the instrumentation tests</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d69cd86d172da2007dfdfeab6c6b3f/href">https://medium.com/media/e3d69cd86d172da2007dfdfeab6c6b3f/href</a></iframe><p>The <strong>instrumentation-tests</strong> job is similar to the <strong>unit-tests</strong> job.<br>The job checkouts code, restores cache, installs Fastlane.<br>After all these steps, the GCLOUD_SERVICE_KEY variable is going to be stored in a file, so after that, it will be possible to authorize with this key and run the instrumentation tests in Firebase Test Lab.<br>To run the instrumentation test, the job executes bundle exec fastlane instrumentation_tests.</p><p>I want to emphasize that the job will not wait until all of the tests will be finished. This step finishes itself right after the APKs were uploaded. I decided to do this because I do not want to waste build time on waiting for the results. In my opinion, you can check the result in the Firebase console and continue the workflow. But if you do not think so, you can remove the --async in the <strong>run_firebase_tests.sh</strong> script.</p><h4>Publish the app</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd70dc40d61cc68865f32f8984bb2291/href">https://medium.com/media/bd70dc40d61cc68865f32f8984bb2291/href</a></iframe><p>As you can see, the job is quite the same as the previous ones and that is why we will skip some steps.<br>Firstly, the job stores the value of the GOOGLE_PLAY_KEY variable into a file. This file will be used by Fastlane to publish the app (do you remember that we set key’s path when we were initializing Fastlane?).<br>Then, the archive with signing data is going to be downloaded. Also, in the next step, Fastlane downloads project&#39;s metadata.<br>After that, the job executes bundle exec fastlane deploy_internal and the release version of the app will be assembled and publish in the internal track on Google Play.</p><h4>Workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*yJ5Wb0MB9H70ZBE4XfnSSw.png" /></figure><p>The workflow will look like this. We run the unit and the instrumentation tests in parallel. After that, there will be a hold step, it means that the build process is stopped and it is waiting for your approval. As I said early, I added this step because I do not want to waste building time, so you check the instrumentation tests results and if everything is OK, you approve the step. However, you can remove the --async flag and the hold step too, but it will increase <strong>instrumentation-tests</strong> step&#39;s build time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f249a01f1266b37b2946040bdd80bb3b/href">https://medium.com/media/f249a01f1266b37b2946040bdd80bb3b/href</a></iframe><p>Here is the workflow’s code. Its name is <strong>deploy-internal</strong> and it contains 4 jobs. The <strong>unit-tests</strong> and <strong>instrumentation-tests</strong> jobs are running in parallel. The <strong>hold</strong> job waits for the end of the <strong>unit-tests</strong> and the <strong>instrumentation-tests </strong>and also it requires user&#39;s approval. The final job is <strong>deploy-internal</strong>, it will not be run until the <strong>hold</strong> job was approved.</p><h3>Summary</h3><p>Let&#39;s sum everything up. We made a quite simple solution that runs the tests and published the app in the internal track on Google Play and it is completely free, even for the private projects.</p><p>The workflow is extremely simple and it should be improved, but how? I would make one more workflow that would build the app and run the Unit tests for every commit, while the <strong>deploy-internal</strong> workflow would be run only for branches that matched some pattern (e.g. internal/*). Also, I would change the <strong>run_firebase_tests.sh</strong> script, so it would get some arguments, for example, APK paths, device ids, OS versions. Thus, I would have a much more flexible solution.</p><p>Here is a GitHub repository for this article.</p><p><a href="https://github.com/ValeryPonomarenko/AndroidCircleCI">ValeryPonomarenko/AndroidCircleCI</a></p><p>If you have any questions, feel free to ask me in comments or on <a href="https://www.linkedin.com/in/ponomarenkovalery/">LinkedIn</a> and <a href="https://twitter.com/iamvaleroncho">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e716c075b99b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/test-and-publish-your-apps-with-circleci-fastlane-firebase-test-lab-e716c075b99b">Test and publish your apps with CircleCI + Fastlane + Firebase Test Lab</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lifecycle aware Dagger components]]></title>
            <link>https://proandroiddev.com/lifecycle-aware-dagger-components-8c74d01fa15?source=rss-aea50bb898c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c74d01fa15</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Valery Ponomarenko]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 16:07:54 GMT</pubDate>
            <atom:updated>2018-10-22T13:17:09.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqToD2juFmEx_rYb5yOKVQ.jpeg" /><figcaption>&quot;Ottawa road in the evening&quot; by <a href="https://unsplash.com/@marcojodoin">Marc-Olivier Jodoin</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Have you ever written something like this to manage the Dagger components?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f5cd0542004b346234d8802d8d700f/href">https://medium.com/media/79f5cd0542004b346234d8802d8d700f/href</a></iframe><p>In my opinion, managing the Dagger components this way forces you to have a huge application class and also you have to write the getSomeComponent, removeSomeComponent code by yourself. Then, in the activity or fragment, you have to get the application, cast it to the YourApplicationClass. Finally, call the needed method to get the component.</p><p>Another way is to have an appComponent in the application class and build a feature component right in the activity or fragment. Now you don’t have a huge application class, but still, you have to get the application, cast it, then get the appComponent, and finally, build a feature component (or a subcomponent). But there is a problem: how to save the component during configuration changes? Tell you the truth, I don’t know a simple way to do this, that is why I think it is not appropriate to build the components in the activities or fragments.</p><p>There is one more way to manage the Dagger component — is to use the Dagger Android. Yes, everything works well until you have only one component and work with subcomponent. But it will not work if you have a gradle multi-modules project and every module has its own independent Dagger component.</p><p>In this article, I will show you how I solve all these problems described above.</p><h3>Quick overview</h3><p>We will start with the quick overview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*u6fIgNCvawUUzs_V6TO3yQ.png" /></figure><p>The simplified version of the Dagger components management algorithm is described above, and as you can see, it is quite simple. The most interesting part of this algorithm is how to notify the InjectionManager that an activity or fragment is being destroyed without adding a line of code to this activity or fragment.</p><p>To managing the components we will need:</p><p>An <strong>IHasComponent interface</strong>.<br>When a class implements this interface, it means that this class has a component and this component must be stored somewhere.</p><p>An <strong>InjectionManager class</strong>.<br>This class is responsible for managing the components. It knows how to get the components and their key, how to store the components, and also, how to get the stored components by their key or class.</p><p>The last but not the least, a <strong>ComponentsStore class</strong>. This is where the components live.</p><p>We’ve finished with the main components and let’s start coding them!</p><h3>InjectionManager</h3><p>We will start with the IHasComponent interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a3425c1c9fceca54f192c49e179d904/href">https://medium.com/media/2a3425c1c9fceca54f192c49e179d904/href</a></iframe><p>Let’s have a look at this methods:</p><ol><li>getComponent — returns a component. The method’s return type is <strong>Any</strong> because Dagger component doesn’t have a superclass and I don’t want to add it (actually you can store not only Dagger components but also whatever objects you want).</li><li>getComponentKey — returns the component’s key. The key must be unique for every component, otherwise, you might have a wrong component.</li></ol><p>Okay, let&#39;s move further.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d907b89ebddba1d3c6902b02bac809/href">https://medium.com/media/a1d907b89ebddba1d3c6902b02bac809/href</a></iframe><p>The ComponentsStore is responsible for <strong>storing</strong>, <strong>getting </strong>and <strong>removing</strong> the components. Also, there is a findComponent method that returns the first component that meets the given predicate, if the component is not found, the method throws a ComponentNotFoundException. Additionally, I add the isExist method that returns <strong>true</strong> if the container has the given key and <strong>false</strong> otherwise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/097a4eacf6657f4d4be0a53904bf5fde/href">https://medium.com/media/097a4eacf6657f4d4be0a53904bf5fde/href</a></iframe><p>Now let’s have a look at the InjectionManager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ef1ed9ca8db345593aff4cd5e607a28/href">https://medium.com/media/6ef1ed9ca8db345593aff4cd5e607a28/href</a></iframe><p>The InjectionManager has three public methods:</p><ol><li>An init method — adds lifecycle callbacks listeners to the application class, therefore, it will be possible to remove the components when the activities or fragments are being destroyed (I will show you how it works a little bit later, just keep reading).</li><li>A bindComponent method — it checks whether the component for the key exists in the ComponentsStore or not. If the component exists, the method just returns this component, otherwise, the component will be created and stored, and finally, the method returns the component. Hence, that is how the components survive during orientation changes.</li></ol><p>The findComponent methods — there are two versions of the method:</p><ol><li><strong>The first one</strong> is a generic method. The method creates a predicate that will be used for searching for the component. The predicate requires that the component is a <strong>T</strong> (generic type) class, or it is a subclass of <strong>T </strong>or implements the <strong>T</strong> interface.</li><li><strong>The second one</strong> is a facade method. It calls the findComponent method of the ComponentsStore class with the given predicate as an argument.</li></ol><p>We’ve finished with the main components of the system and it is time to know how to observe the activity or fragment lifecycle.</p><h3>Observing activities or fragments lifecycle</h3><p>There two classes/interfaces that allow observing the lifecycle of the activity and fragment.</p><p><strong>The first one</strong> is for observing the lifecycle of the activities. This class is called <a href="https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks">Application.ActivityLifecycleCallbacks</a> and it was added in <strong>API 14</strong>.</p><p><strong>The second one</strong> is for observing the lifecycle of the fragment. This class is called <a href="https://developer.android.com/reference/android/support/v4/app/FragmentManager.FragmentLifecycleCallbacks">FragmentManager.FragmentLifecycleCallbacks</a> and it was added in <strong>support library 25.1.0</strong>.</p><h4>Activity lifecycle</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a6125419520ff6ce9b74f75d80415c6/href">https://medium.com/media/6a6125419520ff6ce9b74f75d80415c6/href</a></iframe><p>We create a helper class that implements the Application.ActivityLifecycleCallbacks and name it ActivityLifecycleHelper. With this class, we are able to observe the activity lifecycle so we can remove the components when the activity is being destroyed, that is why we have the ComponentsStore here. Unfortunately, the Application.ActivityLifecycleCallbacks is an interface, so we have to implement all the methods of this interface, but we need only the onActivityDestroyed and onActivityCreated methods.</p><p>When the onActivityDestroyed method is called, in the first instance, we check if the activity implements the IHasComponent interface because if there is no component, there is no need to remove it. After that, we check if the activity is being destroyed by calling the isFinishing method. If these statements are true, we remove the component for the key that we get by calling the getComponentKey method.</p><p>When the onActivityCreated method is called, we check that the activity is AppCompatActivity. It is important because if the activity is not a subclass of AppCompatActivity, it is impossible to add a fragment lifecycle listener. If the statement is true, we add the fragment lifecycle listener to the support fragment manager. The true value of the second argument of the registerFragmentLifecycleCallbacks method means that this lifecycle listener will be added not only for the current fragment manager but also for every child fragment manager too. We do this because we want to observe the child fragment lifecycle too.</p><h4>Fragment lifecycle</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5fe7f160c7c3131c63bbe1aa6a7b1c6/href">https://medium.com/media/b5fe7f160c7c3131c63bbe1aa6a7b1c6/href</a></iframe><p>Now we create a helper class that extends FragmentManager.FragmentLifecycleCallbacks, so it allows us to observe the fragment lifecycle and remove its component when it is required.</p><p>In this case, we add an isInSaveState field because we don’t want to remove the component when the fragment is in save state (e.g. during orientation changes). We set this field to <strong>true</strong> when the onFragmentSaveInstanceState is called and set to <strong>false</strong> when the fragment is started (onFragmentStarted) or resumed (onFragmentResumed).</p><p>When the onFragmentDestroyed is called, we check if the fragment implements the IHasComponent interface for the same reason that we did it for the activity.</p><p>After that, we check if the activity is being destroyed, we remove the components for the fragment.</p><p>Then, if the activity is not being destroyed and the fragment is in save state, we set the isInSaveState to <strong>false</strong> and finish the method.</p><p>The final check is to check if the fragment’s parent fragment (or parent fragment’s parent fragment and so on) is being destroyed. This step is very important for the child fragments because without it the components for the child fragments will never be removed from the ComponentsStore.</p><p>Lastly, we check if the fragment is removing or any parent fragment is removing. If one of the statements is true, we remove the fragment’s component from the ComponentsStore.</p><p>Wow! That’s all. After all these steps, the components will be removed from the ComponentsStore when its owner (activity or fragment) is removing.</p><h3>How to use</h3><p>Great, we&#39;ve written all the components, but here is a question: how to use them?</p><p>First thing first, add the lifecycle callbacks listeners.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dacd59b4dd571059908fe1d1b2f5db4b/href">https://medium.com/media/dacd59b4dd571059908fe1d1b2f5db4b/href</a></iframe><p>Imagine, that the FirstFragment has a component, so we implement the IHasComponent interface and call the bindComponent method of the InjectionManager class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8174577a3da442801414fcbb620ceb37/href">https://medium.com/media/8174577a3da442801414fcbb620ceb37/href</a></iframe><p>What should we do if the fragment doesn’t have its own component and uses the appComponent to inject the dependencies? In this case, the InjectionManager has the findComponent method. Therefore, we just call it and specify the class of the component and that is all.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76ea4472b512d0f73b6a652e45e515a6/href">https://medium.com/media/76ea4472b512d0f73b6a652e45e515a6/href</a></iframe><p>Also, this method might be used for getting Dagger dependencies to build some components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0830883777b115edd464f63420e0c147/href">https://medium.com/media/0830883777b115edd464f63420e0c147/href</a></iframe><h3>That&#39;s it</h3><p>Thanks for reading, I hope you enjoyed :)</p><p>I’ve published a sample project on <a href="https://github.com/ValeryPonomarenko/ComponentsManager/tree/medium_article">GitHub</a>.</p><p>Also, if you don’t want to write this code, I’ve published a library so you can use it. For more information read <a href="https://github.com/ValeryPonomarenko/ComponentsManager">here</a>.</p><p>If you have any questions, feel free to ask me on <a href="https://www.linkedin.com/in/ponomarenkovalery/">LinkedIn</a>. Also, follow me on <a href="https://twitter.com/iamvaleroncho">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c74d01fa15" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/lifecycle-aware-dagger-components-8c74d01fa15">Lifecycle aware Dagger components</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>