<?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 Georgi Stanev on Medium]]></title>
        <description><![CDATA[Stories by Georgi Stanev on Medium]]></description>
        <link>https://medium.com/@georgi.stanev?source=rss-482c0f146cec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YAkujhTX1AdfppmkfCCeRg@2x.jpeg</url>
            <title>Stories by Georgi Stanev on Medium</title>
            <link>https://medium.com/@georgi.stanev?source=rss-482c0f146cec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:37:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@georgi.stanev/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[ Scaling Flutter Apps with a Module-Based Architecture]]></title>
            <link>https://medium.com/prime-holding-jsc/scaling-flutter-apps-with-a-module-based-architecture-fe5eedff06ef?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5eedff06ef</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Mon, 19 May 2025 07:07:29 GMT</pubDate>
            <atom:updated>2025-10-14T22:40:25.832Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Introduction</h3><p>As Flutter applications grow in complexity, so does the need for a clean, maintainable, and scalable architecture. At <a href="https://wisertech.com/"><strong>Wiser Technology</strong></a>, our Flutter team faced the typical challenges of a growing codebase: long build times, clunky code reviews, merge conflicts, and difficult onboarding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F6ieTNWOe8Iwyidm" /></figure><p>We decided to shift to a <strong>module-based architecture</strong> to solve these issues. This article describes our motivation, how the architecture works, the benefits we’ve experienced, and the trade-offs you should consider before adopting it.</p><h3>💡 Why We Chose Module-Based Architecture</h3><h3>🔹 Code Ownership &amp; Logical Grouping</h3><p>In traditional <strong>feature-based structures</strong>, files are organised by type (widgets, services, models), spreading business logic across the app in a way that feels intuitive — until your app becomes large.</p><p>Here’s what we wanted to fix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wj_Py60gkwqzDGbJz5IVA.png" /></figure><p>In the <strong>module-based approach</strong>, each feature (e.g. User Profile, Notifications, Onboarding) lives inside its own Flutter package under the modules/ directory. Each package contains:</p><ul><li>UI layer</li><li>Business logic</li><li>Dependency injection (DI)</li><li>Data sources and repositories</li><li>Unit and golden tests</li><li>And its own DI config, models, and extension methods</li></ul><p>This keeps things neat and makes PRs easier to read and review.</p><h3>🔹 Streamlined Team Collaboration</h3><p>Each <strong>squad owns one or more modules</strong>, meaning:</p><ul><li>They can build, test, and ship features independently.</li><li>Teams rarely step on each other’s toes.</li><li>New devs can onboard faster by focusing on just one module.</li></ul><p>There are also <strong>shared packages</strong> that all squads contribute to:</p><ul><li>shared: Models, Extensions, Config, Permissions, etc.</li><li>design_system: Common UI components, Colours, Fonts, Spacing</li><li>assets: Icons, Images, Typography</li></ul><p>The application package serves as the integration layer. It wires together the modules, routes, dependency injection, and splash screen logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESP9KnH9lgNQFeAiO0voJw.png" /></figure><h3>🧭 How Routing Works in This Architecture</h3><p>Routing in this architecture is <strong>feature-agnostic</strong>, meaning the application layer doesn’t know the internals of each feature — it just resolves routes.</p><p>Here’s the structure:</p><ol><li><strong>Each module</strong> defines its own RouteModel in the shared package.</li><li>These models describe the intent (e.g., ProfileRoute(profileId)).</li><li>The <strong>Route Resolver</strong> in the application maps them to actual GoRoute paths.</li><li>Communication between features is handled via the <strong>Coordinator</strong>, a globally available BLoC.</li></ol><p>🔒 But there are constraints:</p><ul><li>You <strong>can’t pass module-specific objects</strong> through the Coordinator. You need to use Record types or shared models.</li></ul><p>This design keeps modules decoupled and your routing logic centralised.</p><h3>🧪 Testing Strategy</h3><p>One of the biggest wins of the module-based approach is <strong>testability</strong>:</p><ul><li><strong>Unit and golden tests</strong> live inside each module, keeping them close to the code they validate.</li><li><strong>Integration tests</strong> live in the application package since they span multiple modules.</li><li>Each module has its test dependencies.</li></ul><p>This structure encourages better testing practices and makes CI pipelines faster and more modular.</p><h3>📦 How Dependency Injection Works</h3><p>DI is handled at two levels:</p><ol><li><strong>Within each module</strong>, you define your feature-specific services, blocs, and use cases.</li><li>The <strong>application layer</strong> injects global dependencies like analytics, environment config, or remote services.</li></ol><p>You can think of each module like a mini-app with its own Dagger/Koin-like setup.</p><p>The separation ensures you don’t accidentally leak internal logic across modules. It also keeps your DI setup clean and feature-specific.</p><h3>🎨 Shared Design System</h3><p>The design_system package is where we define all reusable UI components:</p><ul><li>Typography</li><li>Colors</li><li>Button styles</li><li>Input fields</li><li>Layout spacing and padding</li><li>Icons, fonts, images (via assets package)</li></ul><p>This allows teams to build consistent, brand-aligned UIs without duplication.</p><p>Bonus: it’s compatible with<a href="https://pub.dev/packages/widgetbook">widgetbook</a>, so you can visually develop and test your components in isolation.</p><h3>🧱 Folder Structure Overview</h3><p>Here’s a high-level breakdown of what the project looks like:</p><pre>lib/<br>├── app/                         # Main application layer<br>│   ├── lib_router/              # Route resolver and GoRouter config<br>│   ├── envs/                    # Environments: dev, staging, prod<br>│   └── integration_test/        # End-to-end tests<br>│<br>├── modules/<br>│.  ├── notifications/<br>│   ├── users/                   # Feature module<br>│   │   ├── feature_login/       # Widgets and Pages<br>│   │   │  ├── ui/               # Widgets, Pages and BLoCs<br>│   │   │  ├── domain/           # Services and Models<br>│   │   │  ├── data/             # Repositories and data sources<br>│   │   ├── feature_register/    # Feature module<br>│   │   └── tests/               # Unit and golden tests<br>│<br>├── shared/                      # Shared utilities and models<br>│   ├── models/<br>│   ├── errors/<br>│   ├── permissions/<br>│   └── lib_router/              # Route models<br>│<br>├── design_system/<br>│   ├── components/<br>│   ├── typography/<br>│   ├── colors/<br>│   └── spacing/</pre><h3>⚠️ Drawbacks &amp; Things to Watch For</h3><p>This architecture isn’t without its challenges.</p><h3>❌ Overhead for Small Projects</h3><p>If you’re a solo dev or a team of 2–3 working on an MVP or side project, this is <strong>overkill</strong>. You’ll spend more time organising folders and managing packages than building features.</p><h3>❌ More Boilerplate</h3><p>You’ll need to:</p><ul><li>Define your routes in two places (model and resolver)</li><li>Maintain more pubspec.yaml files</li><li>Refactor shared logic into common packages</li></ul><p>It’s a bit more upfront work, but it pays off as your app grows.</p><h3>🔚 Final Thoughts</h3><p>Architecture is all about <strong>trade-offs</strong>. The module-based approach adds some complexity up front, but offers immense value as your team and app scale.</p><p>You get:</p><p>✅ Better code organisation<br> ✅ Clear feature ownership<br> ✅ Scalable testing and DI<br> ✅ Improved team collaboration<br> ✅ A unified design system</p><p>But it comes with:</p><p>⚠️ Extra boilerplate<br> ⚠️ Steeper learning curve<br> ⚠️ More project setup</p><p>For us, it was well worth the trade-off.</p><h3>🛠 Bonus: Tips for Adopting This Architecture</h3><ul><li>Start with a simple feature and extract it into a module.</li><li>Define clear boundaries between shared and module.</li><li>Keep your design system simple at first — just buttons and text styles.</li><li>Use widgetbook to document your UI early.</li><li>Set up automated testing per module to catch bugs early.</li></ul><p>✍️ <em>Written by the Flutter Team @ Wiser Technology</em><br> 📁 Check out our <a href="https://github.com/Prime-Holding/flutter-module-based-architecture">GitHub Architecture Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5eedff06ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/scaling-flutter-apps-with-a-module-based-architecture-fe5eedff06ef">🧱 Scaling Flutter Apps with a Module-Based Architecture</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Foundations for Long-Term Mobile Applications]]></title>
            <link>https://medium.com/prime-holding-jsc/efficient-foundations-for-long-term-mobile-applications-4335dc21d15c?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4335dc21d15c</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[automated-testing]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 11:17:55 GMT</pubDate>
            <atom:updated>2024-01-22T09:15:58.948Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficient Foundations for Building Long-Term Mobile Applications</h3><h3>Introduction</h3><p>Let’s explore the most effective strategies for laying the groundwork for a long-term, complex mobile project that requires a sizable team and years of development. We will use <a href="https://flutter.dev/">Flutter</a> as a cross-platform development technology, so grab your favourite beverage, settle in, and let’s delve into the challenges that lie ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6l4q8CpdTO54E8TW93t_Q.png" /></figure><h4>Setting the Scene</h4><p>Imagine a scenario where a client approaches you with the mandate to undertake a substantial project over the next few years, involving multiple cross-functional teams. The goal is to establish the right foundations from the very beginning, ensuring that a few years down the line you won’t hear the dreaded phrase: “The project is so messy; we need to start over.” We’ve all encountered situations like this at some point, haven’t we? This brings us to our first challenge — creating a comfortable environment to lay the groundwork within a few weeks.</p><h4>The MVP Conundrum</h4><p>However, the comfort of laying the foundation quickly is soon followed by the next challenge: delivering the first version (MVP) within three to four months. This is a common hurdle, given the dynamic nature of today’s business environment. A business idea that is valid now may become obsolete in just a couple of years. Therefore, the need to gather user feedback rapidly becomes paramount!</p><h4>Key Considerations</h4><p><strong>Rapid Foundation Establishment:</strong></p><ul><li>Strategies for efficiently setting up the project’s foundational elements within a short timeframe.</li><li>Tools and methodologies to streamline the initial phases and ensure a solid starting point.</li></ul><p><strong>MVP Delivery Challenges:</strong></p><ul><li>Overcoming obstacles in delivering a Minimum Viable Product within a tight timeframe.</li><li>Balancing speed with quality to meet business demands while maintaining a robust project foundation.</li></ul><h3>Background and Lessons Learned:</h3><p>Now, let me provide some background on where we stand with our colleagues at <a href="https://www.primeholding.com/">Prime Holding JSC</a> and the conclusions we’ve drawn, along with the corresponding solutions we’ve adopted. In 2018, Flutter marked its first stable release, and at that time, the ecosystem was relatively underdeveloped compared to its current state. It was like exploring uncharted territory. In early 2019, our company decided to invest in the technology by focusing on human development, expertise and most importantly tools that allow the development team to build mobile applications faster. We embarked on a massive project with a multinational real estate development company, developing their loyalty platform. With millions of customers and the sheer scale of the project, it presented a significant challenge given the youthfulness of the technology.</p><h4>Further Ventures:</h4><p>Since then we have built more than <strong>10</strong> <strong>Flutter Applications,</strong> among them a corporate banking application in 2021 and a retail banking application in 2023. Throughout these years, the ongoing conversation with colleagues has revolved around understanding what components and tools are necessary to ensure that the applications we develop can achieve their long-term goals.</p><h4>Key Considerations and Challenges:</h4><p>Google emphasises that Flutter is primarily focused on the user interface:</p><blockquote>Flutter is Google’s <strong>UI toolkit</strong> for building natively compiled applications for mobile, web, and desktop from a single codebase.</blockquote><p>As we moved into more substantial projects, the need for third-party packages became apparent. Large-scale applications require robust solutions for:</p><ul><li><a href="#4208">Reactive State Management</a></li><li><a href="#1e6a">Design System</a></li><li><a href="#590b">Pre-Built Functionalities</a></li><li><a href="#4c28">Real-Time Updates</a></li><li><a href="#743e">Localisation</a></li><li><a href="#cdec">Routing With Built-In ACL (a.k.a Permissions)</a></li><li><a href="#c776">Environments (Dev, SIT, UAT, Production)</a></li><li><a href="#67ae">Development Experience</a></li><li><a href="#a7b7">Automated Tests</a></li><li><a href="#8668">Understanding The Customer Base</a></li><li><a href="#fc5e">Catching Product Malfunctions In Real Time</a></li><li><a href="#be7f">Application Network Monitoring</a></li></ul><h4>Standardizing Project Setup with rx_bloc_cli</h4><p>When tackling such vast projects, a common question arises: Why should we spend time on the above challenges over and over again? Why not standardize an approach that could work for a vast majority of cases? Recognizing that there is no one-size-fits-all tool, but there are generic instruments, we concluded that we shouldn’t reinvent the wheel with every project. Therefore, we introduced a package that addresses these challenges comprehensively — <a href="https://pub.dev/packages/rx_bloc_cli"><strong>rx_bloc_cli</strong></a>. This package enables quick project setup, covering all the aspects discussed thus far. Let’s explore how this solution facilitates efficient development in the upcoming sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oemh-ifHoX_0gHBNKKeqVw.png" /></figure><h3>Reactive State Management</h3><p><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">Introducing</a> the Flutter package <a href="https://pub.dev/packages/rx_bloc">rx_bloc</a>, designed to streamline the implementation of the BLoC (Business Logic Component) Design Pattern by leveraging the capabilities of <a href="https://pub.dev/packages/rxdart">reactive streams</a>. By merging these technologies, developers can elevate their asynchronous programming skills and benefit from a concise <a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e#6861">package set,</a> resulting in the creation of robust, scalable, and easily maintainable solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3eL5LC0ev7F0rwyrO9Luw.png" /></figure><h4>Why should I use rx_bloc?</h4><p>When tackling a sophisticated project, the challenge arises in constructing a highly interactive UI and robust business logic, all while managing various data sources such as REST APIs, Web Sockets, Secured Storage, Shared Preferences, etc. To navigate this complexity effectively, a sophisticated architecture is required to facilitate seamless product development. <a href="https://www.youtube.com/watch?v=nVX4AzeuVu8">Here</a> you can learn more about <a href="https://pub.dev/packages/rx_bloc">rx_bloc</a>.</p><h4>Key Benefits:</h4><ol><li><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473#2130"><strong>High Performance</strong></a>, achieved by rebuilding only the necessary part of the widget tree.</li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99#d7f7"><strong>Streamlined</strong></a> Inputs (Events) and Outputs (States), which leads to concise, understandable and flexible contracts.</li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-part-2-faf956f2bd99#6fb8"><strong>Zero-boilerplate</strong></a><strong> BloC</strong>, so that the developers can focus on implementing the business logic.</li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-part-2-faf956f2bd99#c627"><strong>Automatic Loading and Error Handlings</strong></a>, to ensure a responsive application while seamlessly managing unexpected issues, enhancing the user experience.</li></ol><h3>Design System</h3><p>A <a href="https://pub.dev/packages/rx_bloc_cli/example#design-system">design system</a> is a comprehensive set of guidelines, principles, and reusable components that provide consistency and cohesiveness across the entire application. It serves as a central repository of design elements, including typography, colour schemes, spacings, animations and UI components ensuring a unified and seamless user experience. The goal of a design system is to streamline development, enhance collaboration among teams, and maintain visual and functional consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Wkv-zEDgKoESpk5agElJA.png" /></figure><h4>Why should I use a Design System?</h4><p>The reason for using a design system is that it adapts seamlessly for scalability, fostering collaboration and providing a shared language for teams. It guarantees maintainability, centralizing updates and enhancing the user experience through familiarity. Additionally, it acts as a sentinel for brand integrity, enforcing standardized visuals and aligning products seamlessly with the brand image.</p><h4>Key Benefits:</h4><ol><li><strong>Consistency</strong>: Ensures a uniform and professional look across various interfaces and platforms.</li><li><strong>Efficiency</strong>: Streamlines design and development processes by offering reusable components and established guidelines.</li><li><strong>Maintainability</strong>: Centralizes updates and changes, reducing the risk of discrepancies over time and simplifying maintenance.</li></ol><h3>Pre-Built Functionalities</h3><p>Enterprise-Grade Pre-Built Features provide a foundation for robust and scalable application development. These features, designed for enterprise-level projects, offer a multitude of benefits. They ensure consistency, streamline development, enhance security, and expedite the implementation of complex functionalities. Leveraging these pre-built features accelerates the development process, reduces the risk of errors, and fosters a cohesive and reliable application architecture, meeting the demanding standards of enterprise-level projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BMSno0l2zxqmHRttlFJrmA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*JS_UAKa_k_6qmxHRFUYTRw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*76huVArJiLDmrtv7kmaB4A.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*D2fB7n14Z6tMKMuN_teIZQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bs5OUCLwKbNbq6v3RUWrFA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*TIUD91d_G3NPGQmKF3atjw.gif" /></figure><h4>Why should I use Pre-Built Components?</h4><p>Leveraging pre-built components like those offered by the <a href="https://pub.dev/packages/widget_toolkit">widget_toolkit</a> package not only accelerates development by providing lightweight and customizable UI elements but also enhances consistency and efficiency. For instance, <a href="https://pub.dev/packages/widget_toolkit_otp">widget_toolkit_otp</a> expedites secure authentication implementation, <a href="https://pub.dev/packages/widget_toolkit_biometrics">widget_toolkit_biometrics</a> simplifies biometric integration, and <a href="https://pub.dev/packages/widget_toolkit_pin">widget_toolkit_pin</a> streamlines secure PIN code functionality. The integration of a QR scanner through <a href="https://pub.dev/packages/widget_toolkit_qr">widget_toolkit_qr</a> further exemplifies the time-saving advantages of pre-built components. When used alongside the <a href="https://pub.dev/packages/rx_bloc_list">rx_bloc_list</a> package, these components not only reduce development time but also ensure a unified and robust user experience within the <a href="https://pub.dev/packages/rx_bloc"><strong>RxBloc</strong> ecosystem</a>.</p><h4>Packages that we use:</h4><ol><li><a href="https://pub.dev/packages/widget_toolkit"><strong>widget_toolkit</strong></a> — The Widget Toolkit package consists of several lightweight and customisable UI components that boost productivity and reduce development time.</li><li><a href="https://pub.dev/packages/widget_toolkit_otp"><strong>widget_toolkit_otp</strong></a> — Package helping with building SMS or pin code fields and screens in a matter of minutes</li><li><a href="https://pub.dev/packages/widget_toolkit_biometrics"><strong>widget_toolkit_biometrics</strong></a> — A Flutter package that helps users to handle enabling and disabling biometrics in an application</li><li><a href="https://pub.dev/packages/widget_toolkit_pin"><strong>widget_toolkit_pin</strong></a> — This package provides out-of-the-box PIN code functionality, which can be used with biometric authentication.</li><li><a href="https://pub.dev/packages/widget_toolkit_qr"><strong>widget_toolkit_qr</strong></a> — A Flutter package which provides a QR scanner widget easily integrated into the application.</li><li><a href="https://pub.dev/packages/rx_bloc_list"><strong>rx_bloc_list</strong></a> — The rx_bloc_list package facilitates implementing infinity scroll and pull-to-refresh features with minimal setup. This package is meant to be used along with <a href="https://pub.dev/packages/rx_bloc">RxBloc ecosystem.</a></li></ol><p>Of course, this is only a subset of all packages we usually when we start a project. <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/packages/rx_bloc_cli/mason_templates/bricks/rx_bloc_base/__brick__/pubspec.yaml">Here</a> you can see a comprehensive list.</p><h3>Real-Time Updates</h3><p>Real-time updates using <a href="https://pub.dev/packages/rx_bloc_cli/example#realtime-communication">HTTP Server-Side Events (SSE)</a> offer a streamlined approach to push events from the server to the client over a single HTTP connection. SSE enables a continuous flow of updates, enhancing user experiences with live and instant data delivery. This lightweight and straightforward protocol eliminates the need for repeated requests, ensuring real-time information delivery for dynamic mobile applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMcS-R-0aTwK8gEddEWdsQ.png" /></figure><h4>Why should I care about real-time updates?</h4><p>Real-time updates are essential for several reasons. They enable immediate data delivery, ensuring users stay informed in real time. This dynamic experience enhances user engagement and provides timely notifications for crucial messages or changes. Efficient monitoring of time-sensitive data, such as stocks or system statuses, is possible with real-time updates, reducing latency and ensuring a responsive application. This capability not only keeps applications competitive but also adapts well to a variety of scenarios, from live chats and social media feeds to financial updates and collaborative tools. In summary, real-time updates significantly elevate user experience, responsiveness, and the overall effectiveness of dynamic applications.</p><h4>Key Benefits</h4><ol><li><a href="https://github.com/Prime-Holding/rx_bloc/tree/master/packages/rx_bloc_cli/mason_templates/bricks/lib_realtime_communication/__brick__/lib/base"><strong>Pre-Built Infrastructure</strong></a>: SSE requires minimal setup and is often simpler to integrate into existing systems compared to WebSockets, which may involve additional configuration.</li><li><strong>Compatibility</strong>: SSE is supported by standard web servers and works over existing HTTP infrastructure, ensuring broader compatibility.</li><li><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/packages/rx_bloc_cli/mason_templates/bricks/lib_realtime_communication/__brick__/lib/base/repositories/sse_repository.dart"><strong>Fallback Mechanism</strong></a>: In the <a href="https://pub.dev/packages/rx_bloc_cli/example#realtime-communication">rx_bloc_cli</a> we have added a built-in automatic reconnection mechanism, providing a graceful fallback if the connection is interrupted.</li></ol><h3>Localisation</h3><p>In Flutter applications, localization involves adapting the UI and content for different languages and regions. It ensures inclusivity, allowing global access. Key aspects include internationalization, managing translations, structured resource storage, language switching, pluralization, RTL support, and tools like <a href="https://pub.dev/packages/r_flutter#i18n">r_flutter</a> for efficient development. Localization is vital for creating versatile, globally accessible apps with a personalized user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Btv0nWwCxggTAnIYz_C4Yg.png" /></figure><h4>Why should I use localisation in my project?</h4><p>Integrating localization into your project is essential for achieving global reach and user engagement. Beyond language translation, it demonstrates cultural sensitivity, ensures legal compliance, and enhances market competitiveness. Offering a customized user experience fosters positive brand perception, potentially increasing revenue. Moreover, localization adapts your project to evolving language trends, making it more adaptable and user-friendly in diverse markets. In summary, localization is a strategic decision that goes beyond translation, contributing to the overall success and resonance of your project on a global scale.</p><h4>Key Benefits:</h4><ol><li><strong>Seamless Integration in the widgets</strong>: Developers can <a href="https://github.com/Prime-Holding/rx_bloc/blob/7e1f910532a8530c0640f060fee1ea04843484bf/packages/rx_bloc_cli/mason_templates/bricks/rx_bloc_base/__brick__/lib/feature_profile/views/profile_page.dart#L66">easily integrate </a>translations into the code by importing the <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/packages/rx_bloc_cli/mason_templates/bricks/rx_bloc_base/__brick__/lib/feature_profile/views/profile_page.dart#L10C15-L10C34">app_extensions.dart</a> file.</li><li><a href="https://pub.dev/packages/rx_bloc_cli/example#remote-localization-lookup"><strong>Remote Localization Lookup</strong></a>: Supports fetching remote localizations during app start, allowing dynamic updates without requiring a new app release.</li><li><a href="https://pub.dev/packages/r_flutter#organize-i18n-strings-by-feature"><strong>Organize I18n strings by feature</strong></a>: Adopts a structured naming scheme for keys, including feature names and separators, promoting clarity and organization.</li></ol><h3>Routing With Built-In ACL (a.k.a Permissions)</h3><p>Efficient <a href="https://pub.dev/packages/rx_bloc_cli/example#routing">routing</a> and robust <a href="https://pub.dev/packages/rx_bloc_cli/example#access-control-list">access control</a> are pivotal components for a seamless user experience and achieving the needed security as well. We decided to integrate the <a href="https://pub.dev/packages/go_router"><strong>go_router</strong></a>, which is a Flutter Routing Package employing a declarative approach, utilizing the <a href="https://blog.codemagic.io/flutter-navigator2/">Navigator 2.0</a> API to offer a user-friendly, URL-based interface for seamless navigation across various screens. This package allows you to define URL patterns, navigate via URLs, manage deep links, and address various other navigation-related scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-nDA3Q1cxW7uIyTc14ztw.png" /></figure><h4>Navigating with RouterBloc:</h4><p>The navigation layer is managed by the <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/packages/rx_bloc_cli/mason_templates/bricks/lib_router/__brick__/lib/lib_router/blocs/router_bloc.dart">lib/lib_router/bloc/router_bloc.dart</a>, allowing for fine-grained control over each route. Developers can perform actions such as pushing, popping, navigating to specific locations, and more, using the following snippets:</p><pre>context.read&lt;RouterBlocType&gt;().events.push(MyNewRoute())<br>context.read&lt;RouterBlocType&gt;().events.pop(MyCustomObject())<br>context.read&lt;RouterBlocType&gt;().events.goToLocation(&#39;/users/123&#39;)<br>context.read&lt;RouterBlocType&gt;().events.pushReplacement(MyNewRoute())<br>context.read&lt;RouterBlocType&gt;().events.go(MyNewRoute())</pre><h4>How do I protect the pages of my application?</h4><p>Ensuring secure access to various app routes is made effortless with <a href="https://pub.dev/packages/rx_bloc_cli/example#access-control-list">ACL</a>. By default, the access to each page can be controlled remotely through the corresponding API endpoint /api/permissions. Let&#39;s explore the expected API response structure for both anonymous and authenticated users.</p><p>Expected API Response for <strong>Anonymous Users</strong>:</p><pre>{<br>    &#39;SplashRoute&#39;: true,<br>    &#39;ProfileRoute&#39;: false,<br>    // Additional routes...<br>}</pre><p>Expected API Response for <strong>Authenticated Users</strong>:</p><pre>{<br>    &#39;SplashRoute&#39;: true,<br>    &#39;ProfileRoute&#39;: true,<br>    // Additional routes...<br>}</pre><h4>Key Benefits:</h4><ol><li><a href="https://pub.dev/packages/rx_bloc_cli/example#access-control-list"><strong>Integrated ACL</strong></a><strong>: </strong>The built-in Access Control List (ACL) simplifies user access management by effortlessly defining and enforcing permissions for specific app routes. Enhance security and streamline access control within your application effortlessly.</li><li><a href="https://pub.dev/documentation/go_router/latest/topics/Configuration-topic.html"><strong>Flexible URL Parsing</strong></a>: Easily parse path and query parameters using a template syntax like “user/:id?param1=someValue”, providing a flexible and intuitive way to handle dynamic content and user-specific routes.</li><li><a href="https://pub.dev/documentation/go_router/latest/topics/Redirection-topic.html"><strong>Dynamic Redirection Support</strong></a>: Seamlessly redirect users to different URLs based on the application state. This is particularly useful for scenarios like redirecting unauthenticated users to a sign-in page, enhancing the overall user authentication flow.</li></ol><h3>Environments (Dev, SIT, UAT, Production)</h3><p>In the dynamic realm of software development, distinct environments — DEV, SIT, UAT, and Production — play crucial roles in ensuring a smooth deployment process. Each flavour is technically a separate application, which allows each environment to be configured and tested individually. Let’s quickly navigate through each phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRmfpGunNRRhUalExZcPzQ.png" /></figure><h4>DEV (Development)</h4><ul><li><strong>Purpose</strong>: Foundation for code creation and experimentation.</li><li><strong>Activities</strong>: Rapid prototyping, unit testing, and continuous integration.</li></ul><h4>SIT (System Integration Testing):</h4><ul><li><strong>Purpose</strong>: Integration testing for seamless system cohesion.</li><li><strong>Activities</strong>: Verification of inter-component interactions and data flow by QA Engineers.</li></ul><h4>UAT (User Acceptance Testing):</h4><ul><li><strong>Purpose</strong>: User-centric validation pre-production.</li><li><strong>Activities</strong>: End-to-end testing, user acceptance validation, and final checks by business representatives.</li></ul><h4>Production:</h4><ul><li><strong>Purpose</strong>: Ultimate deployment for real-world use.</li><li><strong>Activities</strong>: Controlled deployment, real-time monitoring, and continuous improvement.</li></ul><h3>Development Experience</h3><p>In the fast-paced world of mobile application development, experience plays a pivotal role in determining the success and efficiency of a project. Seasoned developers bring a wealth of knowledge, problem-solving skills, and a deep understanding of the intricacies involved in creating robust mobile applications, but regardless of how experienced they are once provided with the needed tools for streamlining the development process, the project timeline could look much more attractive than before. IntelliJ (Android Studio) plugins such as <a href="https://plugins.jetbrains.com/plugin/16165-rxbloc">RxBloc</a> can greatly increase development efficiency as explained below, but before that let’s install it easily from the market. Open your <a href="https://developer.android.com/studio">Android Studio</a>, open the Plugins section, search for RxBloc and hit the install button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2Ip7uycX0t3Zb04BrGJcw.png" /></figure><h4>How the <a href="https://plugins.jetbrains.com/plugin/16165-rxbloc">RxBloc</a> Plugin can boost development efficiency?</h4><p><a href="https://plugins.jetbrains.com/plugin/16165-rxbloc">This plugin</a> saves time and effort when it comes to creating Features, <a href="https://pub.dev/packages/rx_bloc_list">Rx BloC List</a>, <a href="https://pub.dev/packages/rx_bloc">Rx BloC Class</a> or Test Suits for an already existing feature.</p><h4><strong>Facilitate the initiation of your feature effortlessly.</strong></h4><p>Why do we need to spend time creating all needed classes and folders when creating new features?</p><p>Just right-click on the `lib` folder -&gt; New -&gt; RxBloc Feature</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ijnm3NwZxvWo5zXPeISizQ.png" /></figure><p>Fill in the needed details, such as Name, Routing Integration etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iztFkc0_pzfZziLl9MqpYw.png" /></figure><p>Then all needed folders, classes and routing integrations will be created for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*eE29QSgYG_i1UlY9mkO44A.png" /></figure><h4>Add dynamic data to your existing widgets</h4><p>Wrap the widgets of your existing widget tree with the <a href="https://pub.dev/packages/flutter_rx_bloc">RxBloc-related widgets</a>, which work as a binder of the Business and the UI layer. Just click on the widget that needs to consume dynamic data, and select the wrapper you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LF7Xzf2aPrpomknaZB2jA.png" /></figure><p>and then you can start consuming the BloC State</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bvjfg1sOVCaH4wjEUg2qjQ.png" /></figure><h4>Key Benefits:</h4><ol><li><strong>Unified Feature Structure</strong>: <em>Streamlined Development:</em> Fosters a consistent feature structure for efficient and collaborative development.</li><li><strong>Seamless Widget Wrapping</strong>: <em>Enhanced Integration:</em> Simplifies widget integration, promoting cleaner code and accelerated development.</li><li><strong>Unit Tests Bootstrapping</strong>: <em>Efficient Testing:</em> Facilitates easy unit test set-up, ensuring robust testing for reliable code.</li></ol><h3>Automated Tests</h3><p>Integration tests validate the functionality of our Flutter applications at a broader level and assess the entire application as a cohesive unit, including its interactions and dependencies. While unit tests focus on isolated units of code. Apart from those well-known testing approaches, in Flutter we have <a href="https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter">Golden Tests</a>, which help maintain pixel-perfect applications.</p><h4>Unit Tests</h4><p>Unit tests in software development evaluate individual code units, such as functions or methods, to ensure they perform as expected in isolation. These tests help identify and fix errors early in the development process, promoting code reliability and maintainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSsULET-DQm8BKqo52myUQ.png" /></figure><h4>Key Features</h4><ul><li><a href="https://pub.dev/packages/rx_bloc_test#rxbloctest"><strong>rxBlocTest</strong></a><strong>: </strong>Simplifies and minimises the code needed for testing the Business Logic Components</li><li><a href="https://pub.dev/packages/rx_bloc_test#rxblocfakeasynctest"><strong>rxBlocFakeAsyncTest</strong></a><strong>: </strong>Speed up the tests, which require back pressure operators such as <a href="https://pub.dev/documentation/rxdart/latest/rx/DebounceExtensions.html">debounce</a>, <a href="https://pub.dev/documentation/rxdart/latest/rx/ThrottleExtensions.html">throttle</a> etc.</li></ul><h4>Golden Tests</h4><p>In Flutter, golden tests are a type of UI testing that focuses on capturing and comparing the visual appearance of widgets. Instead of asserting specific widget states or properties, golden tests create and store “golden” images representing the expected appearance of UI components. During subsequent test runs, the actual UI is compared against these golden images, helping developers identify visual changes or regressions in the application’s user interface. Golden tests are particularly useful for maintaining consistent and visually appealing UIs across different platforms and releases in Flutter applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhL7doX-PILHK43kr7GJ1g.png" /></figure><h4>Key Features</h4><ul><li><a href="https://pub.dev/packages/golden_toolkit#goldenbuilder"><strong>GoldenBuilder</strong></a>: The GoldenBuilder class lets you quickly test various states of your widgets given different sizes, input values or accessibility options.</li><li><a href="https://pub.dev/packages/golden_toolkit#devicebuilder"><strong>DeviceBuilder</strong></a>: DeviceBuilder class is like the GoldenBuilder except that it constrains scenario widget sizes to Device configurations. This removes the need to specify a column or grid-based layout.</li><li><a href="https://pub.dev/packages/golden_toolkit#multiscreengolden"><strong>multiScreenGolden</strong></a>: The multiScreenGolden assertion is used to capture multiple goldens of a single widget using different simulated device sizes &amp; characteristics.</li></ul><h4>Integration Tests</h4><p>End-to-end (E2E) testing provides a comprehensive evaluation of the entire application, examining its functionality from the user’s perspective as a complete, integrated system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62c7apFouiTmJU-roVlOnA.png" /></figure><h4><strong>Key Benefits:</strong></h4><ol><li><strong>A Powerful Tool</strong>: Our chosen tool for integration testing is <a href="https://pub.dev/packages/patrol">Patrol</a>, a versatile package that extends beyond Flutter’s context.</li><li><strong>Access to Specific Controls</strong>: Patrol provides access not only to the application’s surface but also to specific native controls such as push notifications, biometrics etc</li><li><strong>Making the Impossible Possible</strong>: Patrol, as claimed by its developers, empowers developers to achieve the seemingly impossible.</li></ol><h3>Understanding The Customer Base</h3><p>From my perspective, this tool is absolutely necessary for any application, impacting every facet of its existence. After all, what we’re developing is a product, and for any product to thrive, understanding its end users is paramount. We need to know who they are, where they are, and which screens of our product they visit the most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCk09n5MZRApuQ6Q0fm3Bw.png" /></figure><h4><strong>Why Firebase Analytics?</strong></h4><p>Our choice of Firebase Analytics is multi-faceted. Firstly, it boasts excellent integration capabilities with Flutter, ensuring a seamless experience within our development environment. Secondly, the service provided by Firebase Analytics is free of charge, a crucial factor for many projects. Last but not least, the fantastic support from Google further solidifies our decision.</p><h4>Key Benefits:</h4><ol><li>Seamless Flutter Integration: Enjoy smooth integration, minimizing development efforts.</li><li>Cost-Effective: Benefit from Firebase Analytics’ cost-free service.</li><li>Google Backing: Rely on robust support and continuous improvements from Google.</li></ol><h3>Catching The Product Malfunctions In Real Time</h3><p>Continuing our toolkit exploration, let’s delve into Crashlytics, a pivotal tool for error monitoring in Firebase. Whether we’re discussing an enterprise-level overview or a smaller-scale project, the need for error monitoring is universal.</p><h4>The Imperfection of Software:</h4><p>In the realm of software development, perfection remains elusive. Even tech giants like Facebook and Google encounter regressions. As developers, it’s crucial to acknowledge that imperfections exist. To identify and rectify issues efficiently, a reliable tool is indispensable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYivgOjRZaBSTFMCPYEQaQ.png" /></figure><h4>Why Crashlytics?</h4><p>Crashlytics stands out as a robust solution for error monitoring within the Firebase ecosystem. Here’s why it’s a crucial addition to our toolkit:</p><ol><li>Real-time Error Reporting: Instantly detect and report crashes, enabling swift response to emerging issues.</li><li>Comprehensive Crash Reports: Access detailed crash reports, aiding in the identification of root causes.</li><li>Prioritization of Fixes: Prioritize fixes based on the severity and impact of each issue.</li></ol><h3>Application Network Monitoring</h3><p>Application Network Monitoring involves the continuous observation and analysis of an application’s network activities. It aims to ensure optimal performance, detect potential issues, and enhance overall reliability. By monitoring network metrics, traffic patterns, and communication between the mobile application and its API, the developers can proactively identify bottlenecks, troubleshoot problems, and maintain the health and efficiency of their applications.</p><h4>Embedded Network Monitoring</h4><p>There are scenarios where we need to quickly debug our application by monitoring the API Requests directly from our phone. Here we found <a href="https://pub.dev/packages/alice">Alice</a>, an HTTP Inspector tool that helps debug http requests. It catches and stores HTTP requests and responses, which can be viewed via simple UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fUrVWpmRlebrBLB2xWgyA.png" /></figure><h4>Key Features:</h4><ul><li><strong>Inspector UI</strong> for viewing HTTP calls.</li><li><strong>Notification</strong> on HTTP call.</li><li><strong>Support</strong> for top-used HTTP clients in Dart (<a href="https://pub.dev/packages/dio">Dio</a>, <a href="https://api.dart.dev/stable/3.2.4/dart-io/dart-io-library.html">dart:io</a>, <a href="https://pub.dev/packages/http">http package</a>, <a href="https://pub.dev/packages/chopper">Chopper</a>).</li></ul><h4>Web Proxy with Charles</h4><p>Charles Web Debugging Proxy is a cross-platform HTTP debugging proxy desktop application. It enables the user to view HTTP, HTTPS, and HTTP/2 and allows TCP port traffic accessed from, to, or via the local computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdgAyU2SqFoCdMOeVxNIZw.png" /></figure><h4>Key Features:</h4><ol><li><strong>HTTP and SSL/TLS Traffic Monitoring</strong>: Charles serves as an HTTP proxy, facilitating the monitoring and debugging of HTTP and encrypted SSL/TLS traffic between applications and the internet.</li><li><strong>SSL Proxying</strong>: The tool supports SSL proxying, enabling users to inspect and debug encrypted SSL/TLS traffic, aiding in the identification and resolution of security-related issues.</li><li><strong>Dynamic Request and Response Manipulation</strong>: Charles allows on-the-fly modification of HTTP requests and responses, offering flexibility in testing scenarios and optimizing web application functionality.</li></ol><h3>Conclusion</h3><p>Within the realm of mobile development, the <a href="https://www.primeholding.com/">Prime Holding JSC</a> services offer a distinctive value proposition. Specializing in Flutter technology since 2019, our emphasis on user-centric development, efficiency, and consistency sets us apart. We have adapted bullet-proofed, standardized solutions for automated testing, analytics, error monitoring, real-time updates, localization, routing, multi-environment deployment and all you need to take your application to the next level. Prime Holding’s commitment to experience, expertise, and proactivity positions us as a valuable partner in navigating the dynamic mobile development landscape.</p><h4>Related articles</h4><ol><li><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">Introducing rx_bloc ecosystem — Part 1</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99">Introducing rx_bloc: Part 2</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473">Introducing flutter_rx_bloc: Part 3</a></li><li><a href="https://medium.com/prime-holding-jsc/rxbloc-intellij-plugin-d1d2ddfb7628">RxBloc Intellij Plugin</a></li><li><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building forms in Flutter</a></li><li><a href="https://medium.com/prime-holding-jsc/easy-paginated-lists-in-flutter-b1cfb82188d8">Easy Paginated Lists In Flutter</a></li><li><a href="https://medium.com/prime-holding-jsc/bootstrapping-your-flutter-app-with-ease-7efad0aa697a">Bootstrapping Your Flutter App With Ease</a></li><li><a href="https://medium.com/prime-holding-jsc/inter-feature-communication-in-flutter-apps-c6b14e944ac3">Inter-feature communication in Flutter apps</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4335dc21d15c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/efficient-foundations-for-long-term-mobile-applications-4335dc21d15c">Efficient Foundations for Long-Term Mobile Applications</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inter-feature communication in Flutter apps]]></title>
            <link>https://medium.com/prime-holding-jsc/inter-feature-communication-in-flutter-apps-c6b14e944ac3?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b14e944ac3</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 09:05:09 GMT</pubDate>
            <atom:updated>2022-06-10T09:29:33.028Z</atom:updated>
            <content:encoded><![CDATA[<p>What does inter-feature communication in the context of mobile applications mean and why do we even need it? Let’s face it, users nowadays are more spoiled than ever. To satisfy their expectations, most modern apps need to provide highly interactive UX. This means that when the user executes an action on a particular page they expect the data they work with to be up-to-date all the time in the entire application. Let’s take a look at the famous <a href="https://apps.apple.com/us/app/reminders/id1108187841">Reminders App</a>, where the user creates a reminder from the <strong>Reminder List</strong> Page, and the respective count in the <strong>Dashboard</strong> Page is refreshed automatically.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0Rzphoei71k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0Rzphoei71k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0Rzphoei71k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ddb00270607a30e3aa1c90ac299a20/href">https://medium.com/media/94ddb00270607a30e3aa1c90ac299a20/href</a></iframe><p>So now the question is how can we as developers implement this behavior most efficiently? If you are new to Flutter don’t be scared. This is easily achievable especially if you have the utilities you need in your state <a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">management solution</a>. Let’s see how we can implement this behavior using the <a href="https://pub.dev/packages/rx_bloc">rx_bloc</a> package.</p><h3>Event-based approach</h3><p>We have two pages, the <strong>Dashboard </strong>Page<strong> </strong>and the <strong>Reminder List</strong> Page. They are decoupled from each other but in order to implement the needed functionality, we need to establish the <strong>inter-feature communication channel</strong>, where our choice is the <strong>Coordinator</strong> Pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIahEOtMgOTUYnkS22JsZg.jpeg" /></figure><p>Whenever the user updates/deletes/create a reminder in the <strong>Reminder List</strong> Page an event is sent to the <strong>Coordinator, </strong>and all pages (such as the <strong>Dashboard</strong>) receive the reminder so they can update their own state (in our case the count of reminders). Sounds clean, doesn’t it? Let’s see some code.</p><h3>Sending the created reminder to the Coordinator</h3><p><strong>The UI Layer</strong></p><pre>...<br>ElevatedButton(<br>    child: Text(&#39;Submit&#39;),<br>    <strong>onPressed</strong>: () =&gt; context<br>        .read&lt;ReminderListBlocType&gt;()<br>        .events<br>        .<strong>create</strong>(_titleEditingController.text)<br>)<br>...</pre><p>From the UI Layer (a.k.a the widget tree) we simply call the `create` event as passing the title of the reminder.</p><p><strong>The Business Layer</strong></p><pre>class ReminderListEvents {<br>  <br>  /// Create a reminder with the provided [title]<br>  void <strong>create</strong>(String title);<br>}</pre><pre>class ReminderListStates{<br> <br>  /// The state of the newly created reminder<br>  Stream&lt;<strong>ReminderModel</strong>&gt; get <strong>onReminderCreated</strong>;<br>}</pre><pre>@RxBloc()<br>class ReminderListBloc extends $ReminderManageBloc {<br><br>  final RemindersService _service;<br>  final CoordinatorBloc _coordinatorBloc;<br><br><br>  @override<br>  Stream&lt;<strong>ReminderModel</strong>&gt; _mapToOnReminderCreatedState() =&gt;<br>      <strong>_$createEvent</strong><br>          .asyncMap((title) =&gt; _service.<strong>create</strong>(title: title))<br>          .doOnData(_coordinatorBloc.events.<strong>reminderCreated</strong>);<br>...<br>}</pre><p>Once the UI Layer sends the reminder’s title through the <strong>create(title)</strong> event, the subject of which is <strong>_$createEvent, </strong>we try to save the reminder in the API. In case it’s saved successfully the created reminder is sent to the <strong>CoordinatorBloc.</strong></p><h3>Receiving updates</h3><p><strong>The Business Layer</strong></p><pre>abstract class DashboardStates {<br>    @<strong>RxIgnoreState</strong>()<br>    Stream&lt;DashboardModel&gt; get <strong>dashboard</strong>;<br>}</pre><pre>@RxBloc()<br>class DashboardBloc extends $DashboardBloc {<br>  DashboardBloc(CoordinatorBloc <strong>coordinatorBloc</strong>) {<br><br>    <strong>coordinatorBloc</strong>.states<br>        .<strong>reminderCreated</strong><br>        .map((<strong>reminder</strong>) =&gt; _<strong>copyDashboardWithReminder(reminder)</strong>)<br>        .<strong>bind</strong>(_dashboardModel)<br>        .addTo(_compositeSubscription);<br>  }</pre><pre>  /// Copy the  DashboardModel with calculated count <br>  /// based on the passed [reminder] object.<br>  DashboardModel <strong>_copyDashboardWithReminder</strong>(<br>      ReminderModel reminder<br>  ) {<br>   ...... <br>  }</pre><pre>  /// The internal state of the <strong>dashboard model</strong><br>  final _dashboardModel = BehaviourSubject&lt;DashboardModel&gt;()</pre><pre>  <strong>@override</strong><br>  Stream&lt;DashboardModel&gt; get dashboard =&gt; _dashboardModel;</pre><pre>  ....<br>}</pre><p>The <strong>Dashboard</strong> BloC listens for the reminder “created event” and when such is received the <strong>_copyDashboardWithReminder </strong>is being called.<strong> </strong>This<strong> </strong>increases the count based on the received object, then the whole dashboard model is updated and the UI layer updates accordingly so that the user can see the change.</p><p><strong>The UI Layer</strong></p><pre>...<br>RxBlocBuilder&lt;DashboardBlocType, DashboardModel&gt;(<br>  <strong>state</strong>: (bloc) =&gt; bloc.states.<strong>dashboard</strong>,<br>  <strong>builder: </strong>(context, dashboardModel, bloc) =&gt; ...,<br>)<br>...</pre><p>In the widget tree, we simply listen for any state change of the <strong>dashboard model </strong>and then build the appropriate UI representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsAWD-rw6hE0J7pTRgSHuA.jpeg" /></figure><h3>Conclusion</h3><p>In this article, you learned how to satisfy the user expectations of having up-to-date data in your application without any user interaction. We achieved this by building a simple, scalable, and easy-to-use inter-feature communication channel. In the following article, we will dive deep into more complex scenarios where a single reminder will be automatically refreshed on Page X when updated on Page Y.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b14e944ac3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/inter-feature-communication-in-flutter-apps-c6b14e944ac3">Inter-feature communication in Flutter apps</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Forms in Flutter]]></title>
            <link>https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/454b8d65f48</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 15:10:32 GMT</pubDate>
            <atom:updated>2021-02-24T07:46:54.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Although building forms in Flutter may seem like an easy task, separating the business logic from the UI layer can be a challenge. The separation of concerns makes your app more scalable and maintainable and most importantly the business (validation) logic becomes unit-testable, so let’s see how we can achieve this by using <a href="https://pub.dev/packages/rx_bloc"><strong>rx_bloc</strong></a><strong> </strong>and<strong> </strong><a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong>. </strong>If you are new to <a href="https://pub.dev/packages/rx_bloc">rx_bloc</a>, check out <a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e"><strong>Introducing rx_bloc ecosystem</strong></a><strong>. </strong>As<strong> </strong>usual, we will be using our lovely <a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">puppies sample</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYDN5ISRm_FY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYDN5ISRm_FY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYDN5ISRm_FY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a07516543ff573b4c6f3b24cb43572b/href">https://medium.com/media/3a07516543ff573b4c6f3b24cb43572b/href</a></iframe><h3>Building the business logic</h3><p>First, we need to declare the <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L11"><strong>events</strong></a> and <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L27"><strong>states</strong></a> contracts for the BloC we are about to implement. In our case, it will be the <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart">PuppyManageBloc</a> that will be responsible for creating and updating a puppy.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L99">puppy_manage_bloc.dart</a></p><pre><br>abstract class PuppyManageEvents {</pre><pre>   void setName(String name);</pre><pre>   void savePuppy();<br>   ...<br>}</pre><pre>abstract class PuppyManageStates {</pre><pre>   Stream&lt;String&gt; get name;<br>   ...<br>}</pre><p>As you can see above, in the <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L11"><strong>events</strong></a><strong> </strong>contract<strong> </strong>we have two events, one for setting the name and one for saving the entity. Then in the <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L27"><strong>states</strong></a> contract, we declare just the name of the puppy.</p><p><strong>How to prefill the form?</strong></p><p>The form for creating a puppy should be empty because the puppy has not been created yet, but when it comes to updating a puppy, we need to prefill all the fields related to the properties of the puppy that we want to update. For simplicity, let’s just showcase the puppy’s name.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L99">puppy_manage_bloc.dart</a></p><pre><a href="http://twitter.com/RxBloc">@RxBloc</a>()<br>class PuppyManageBloc extends $PuppyManageBloc {<br>  PuppyManageBloc(<br>    this.puppy,<br>    ...<br>  })</pre><pre><a href="http://twitter.com/override">  @override</a>   <br>  Stream&lt;String&gt; _mapToNameState() =&gt; _$setNameEvent<br>      .<strong>startWith(puppy?.name ?? &#39;&#39;)</strong><br>      ...<br>}</pre><p>In the event-to-state mapper <a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L99">_mapToNameState</a>, we declare with the <a href="https://pub.dev/documentation/rxdart/latest/rx/StartWithExtension/startWith.html">startWith</a> operator that the first event that will be sent to the UI Layer will be the name of the puppy we are updating, which will prefill the text field. How easy is that?</p><h4>Error handling</h4><p>Now the question is how do we handle the errors if the puppy’s name is <em>empty</em> or <em>too long</em>? Fortunately, Dart Streams support errors (as explained <a href="https://dart.dev/tutorials/language/streams#error-events"><strong>here</strong></a>),<strong> </strong>and<strong> </strong><a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong> </strong>leverages this in <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFieldException-class.html"><strong>RxFieldException</strong></a> which helps us show a user-friendly message next to the field where the error occurs.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart#L99">puppy_manage_bloc.dart</a></p><pre><a href="http://twitter.com/RxBloc">@RxBloc</a>()<br>class PuppyManageBloc extends $PuppyManageBloc {<br>  PuppyManageBloc(<br>    this.validator,<br>    this.repository,<br>    this.puppy,<br>    ...<br>  })</pre><pre>  final PuppyValidator validator;</pre><pre><a href="http://twitter.com/override">  @override</a>   <br>  Stream&lt;String&gt; _mapToNameState() =&gt; _$setNameEvent<br>      .startWith(puppy?.name ?? &#39;&#39;)<br>      .<strong>map(validator.validatePuppyName</strong>);<br>}</pre><p>The validation logic will be triggered on the fly when the user starts typing, as the events will sink into the <strong>_$setNameEvent</strong>subject by calling <strong>setName(name:).</strong> Now let’s see what the actual validation logic looks like</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a29120170cb48930a15187af46b35b82c29ba375/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/validators/puppy_validator.dart#L16">puppy_validator.dart</a></p><pre>class PuppyValidator {</pre><pre>  String validatePuppyName(String name) {<br>    if (name == null || name.isEmpty) {<br>      throw RxFieldException(<br>        fieldValue: name,<br>        error: &#39;Name must not be empty.&#39;,<br>      );<br>    }</pre><pre>    if (name.trim().length &gt; _maxNameLength) {<br>      throw RxFieldException(<br>        fieldValue: name,<br>        error: &#39;Name is too long.&#39;,<br>      );<br>    }</pre><pre>    return name;<br>  }<br>}</pre><p>In the validator, we handle two error scenarios “<strong>Name must be not empty” </strong>and “<strong>Name is too long&quot;</strong>. As you can see the validator either throws a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFieldException-class.html">RxFieldExceptio</a>n or just returns the puppy’s name. Throwing exactly this type of exception is important because it allows us to combine the error message with the current value in the business logic, and consequently we can declare in the UI layer what the field should contain and what the error message should look like.</p><h3>Building the UI layer</h3><p>Our business layer is ready, so now we can start building the UI layer and all necessary bindings. Following best practices, we need to create a dedicated widget for the page and a widget for the form itself.</p><h4>The page widget</h4><p>This widget will be responsible for the DI (<a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a>), scaffold, and the app bar, so let’s see what the implementation looks like.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/edit/views/puppy_edit_page.dart"><strong>puppy_edit_page.dart</strong></a></p><pre>class PuppyEditPage extends StatelessWidget with AutoRouteWrapper {</pre><pre>  final Puppy _puppy;</pre><pre><a href="http://twitter.com/override">  @override</a><br>  Widget <strong>wrappedRoute</strong>(BuildContext context) =&gt;<br>    <strong>RxBlocProvider</strong>&lt;PuppyManageBlocType&gt;(<br>      create: (context) =&gt; PuppyManageBloc(<br>        puppy: puppy,<br>        repository: context.read(),<br>        validator: context.read(),<br>      ),<br>    ),<br>    child: this,<br>  );</pre><pre><a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) =&gt; <br>    Scaffold(<br>      appBar: PuppyEditAppBar(),<br>      body: RxUnfocuser(<br>        <strong>PuppyEditForm</strong>(<br>          puppy: puppy,<br>        )<br>      ),<br>    );<br>}</pre><p>As you can see, we leverage the <a href="https://pub.dev/packages/auto_route">auto_router</a> package, using the <a href="https://pub.dev/packages/auto_route#handling-wrapped-routes">wrapped route</a> along with the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html"><strong>RxBlocProvider</strong></a> to inject the <strong>PuppyManageBloc</strong>. This way, this BloC will be available within the widget tree of the page and will also be automatically disposed of when the user leaves the page.</p><h4>The form</h4><p>The form widget should only be responsible for the form, which usually contains a column with children that will be the actual form inputs.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/edit/ui_components/puppy_edit_form.dart"><strong>puppy_edit_form.dart</strong></a></p><pre>class PuppyEditForm extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) =&gt; Column(<br>    children: [ <br>      <strong>RxTextFormFieldBuilder</strong>&lt;PuppyManageBlocType&gt;(<br>        state: (bloc) =&gt; bloc.states.name,<br>        showErrorState: (bloc) =&gt; bloc.states.showErrors,<br>        onChanged: (bloc, value) =&gt; bloc.events.setName(value),<br>        builder: (fieldState) =&gt; <strong>TextFormField</strong>(<br>          controller: fieldState.controller,<br>          decoration: fieldState.decoration<br>              .copyWithDecoration(InputStyles.textFieldDecoration),<br>        ),<br>      )<br>      ...  <br>    ]<br>}</pre><p>For each text input, we use <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilder-class.html">Rx</a><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilder-class.html"><strong>Text</strong></a><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilder-class.html">FormFieldBuilder</a>, (or <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFormFieldBuilder-class.html"><strong>RxFormFieldBuilder</strong></a>) where we specify which BloC should be used (in our case <strong>PuppyManageBlocType</strong>). Then we need to specify the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFormFieldBuilder/state.html"><strong>state</strong></a> of the BloC we want to listen to, the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilder/onChanged.html"><strong>event to call</strong></a> when the user is typing, and the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFormFieldBuilder/builder.html"><strong>builder</strong></a> that usually returns a TextFormField but could also return any custom text input that has a decoration.</p><p>As an argument of the builder, we get a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilderState-class.html"><strong>fieldState</strong></a> which contains a bunch of useful properties. One of the most useful properties is the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilderState/controller.html"><strong>controller</strong></a>that should be passed to the field, which works as a communication channel between the business layer and the UI layer. Another is the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxTextFormFieldBuilderState/decoration.html"><strong>decoration</strong></a>, which defines how to be presented the error state, including the border, the message, and much more.</p><p>You might have noticed in the video above that the errors appear only when the user taps on the submit button, which is controlled by the property<a href="https://pub.dev/documentation/flutter_rx_bloc/latest/rx_form/RxFormFieldBuilder/showErrorState.html"><strong>showErrorState</strong></a><strong>.</strong></p><h3>Architecture: the big picture</h3><p>In conclusion, from the user’s perspective, the form looks simple, but as software engineers, we need to deal with a lot of things behind the scenes.</p><p>For this, we need tools like <a href="https://pub.dev/packages/rx_bloc"><strong>rx_bloc</strong></a> to help us build the business layer of the form and like <a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong> </strong>to help us building the UI layer. Let’s see what an architectural diagram of our implementation looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhoV3gKqvf5NF1PTGS5cGQ.jpeg" /></figure><h3>Related articles</h3><ol><li><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">Introducing rx_bloc ecosystem — Part 1</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99">Introducing rx_bloc: Part 2</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473">Introducing flutter_rx_bloc: Part 3</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454b8d65f48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building Forms in Flutter</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing flutter_rx_bloc: Part 3]]></title>
            <link>https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d9114da473</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 15:47:12 GMT</pubDate>
            <atom:updated>2021-02-24T07:50:06.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeGtNvgcjCnOk5CXduN0Aw.png" /></figure><p><strong>The </strong><a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong> </strong>is a <a href="https://flutter.dev/">Flutter</a> package that exposes your <a href="https://pub.dev/packages/rx_bloc">reactive BloCs</a> to the <strong>UI Layer</strong>. In the previous article, <a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99"><strong>Introducing rx_bloc: Part 2</strong></a><strong> </strong>(I recommend that you read it quickly before continuing with this article if you haven’t already)<strong>, </strong>you learned how you can implement the business layer of the <a href="https://pub.dev/packages/flutter_rx_bloc/example">Counter sample</a> and in this article, we’ll see how we can bind it to the UI Layer</p><p>Let’s start with what <a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong> </strong>offers and how it can help us.</p><h3>RxBlocProvider</h3><p><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html"><strong>RxBlocProvider</strong></a> is a Flutter widget that provides a BloC to its children via <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider/of.html">RxBlocProvider.of&lt;T&gt;(context)</a>. It is used as a dependency injection (<strong>DI</strong>) widget so that a single instance of a BloC can be provided to multiple widgets within a subtree.</p><p>In most cases, <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a> should be used to create new BloCs which will be made available to the rest of the subtree. At the same time, <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a> automatically handles closing the BloC as well. This ensures that our BloCs don’t cause any memory leaks.</p><p>Let’s now see how we can create an instance of the <strong>CounterBloc </strong>using<strong> </strong><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html"><strong>RxBlocProvider</strong></a>.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/main.dart#L13"><strong>main.dart</strong></a></p><pre>MaterialApp(<br>    ...<br>    home: <strong>RxBlocProvider</strong>&lt;<strong>CounterBlocType</strong>&gt;(<br>        create: (context) =&gt; <strong>CounterBloc</strong>(CounterRepository()),<br>        child: const <strong>HomePage</strong>(),<br>    ),<br>);</pre><p>In case you need to provide multiple BloCs to the subtree please consider using <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxMultiBlocProvider-class.html">RxMultiProvider</a> as it improves readability and eliminates the need to nest multiple <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a>s.</p><p>In our <a href="https://pub.dev/packages/flutter_rx_bloc/example"><strong>Counter</strong></a> sample, we simply wrap the home page with <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a>, which makes it accessible in the HomePage. However, if you are using any <a href="https://pub.dev/packages/provider">provider</a>-based package such as <a href="https://pub.dev/packages/auto_route"><strong>auto_router</strong></a><strong> </strong>in your project, you can benefit from <a href="https://pub.dev/packages/auto_route#handling-wrapped-routes"><strong>wrapped_route</strong></a><strong>, </strong>which wraps your route with a parent widget like a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a>.</p><h3>RxBlocBuilder</h3><p><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder-class.html"><strong>RxBlocBuilder</strong></a> is a Flutter widget that requires a RxBloc, a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder/builder.html">builder</a>, and a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder/state.html">state</a> function. <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder-class.html">RxBlocBuilder</a> handles building the widget in response to new states. <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder-class.html">RxBlocBuilder</a> is very similar to <a href="https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html">StreamBuilder</a> but has a more simple API to reduce the amount of boilerplate code needed.</p><p>The <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder/builder.html">builder</a> function should be a pure function that returns a widget in response to the state change, which will potentially be called many times.</p><p>The <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder/state.html">state</a> function determines which exact state of the BloC will be used.</p><p>If the <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocBuilder/bloc.html">BloC</a> parameter is omitted, RxBlocBuilder will automatically perform a lookup using <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a> and the current BuildContext.</p><p>Let’s now see how we can access the <strong>count</strong> state from the HomePage</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/pages/home_page.dart#L30"><strong>home_page.dart</strong></a></p><pre>class HomePage extends StatelessWidget {<br>  <strong>@</strong>override<br>  Widget build(BuildContext context) =&gt;<br>    Scaffold(<br>      ...<br>      <strong>RxBlocBuilder</strong>&lt;<strong>CounterBlocType</strong>, <strong>int</strong>&gt;(<br>        <strong>state</strong>: (bloc) =&gt; bloc.states.count,<br>        <strong>builder</strong>: (context, snapshot, bloc) =&gt; <br>          snapshot.hasData ? <br>            Text(snapshot.data.toString()): <br>            Container()<br>  )<br>}</pre><p>In case your state is of the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/Result-class.html"><strong>Result</strong></a><strong> </strong>type, please consider using <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxResultBuilder-class.html"><strong>RxResultBuilder</strong></a><strong>,</strong> which is similar to RxBlocBuilder, but is designed to handle the Result state in an easier way. It provides callbacks such as <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxResultBuilder/buildSuccess.html">buildSuccess</a>, <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxResultBuilder/buildError.html">buildError</a>, and <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxResultBuilder/buildLoading.html">buildLoading</a>.</p><h3>RxBlocListener</h3><p><a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocListener-class.html"><strong>RxBlocListener</strong></a> is a Flutter widget that takes a <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocWidgetListener.html">RxBlocWidgetListener</a> and invokes it in response to a state change in the BloC. It should be used for functionalities that need to occur once per state change such as navigation, showing a SnackBar, showing a Dialog, etc…</p><p>If the BloC parameter is omitted, <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocListener-class.html">RxBlocListener</a> will automatically perform a lookup using <a href="https://pub.dev/documentation/flutter_rx_bloc/latest/flutter_rx_bloc/RxBlocProvider-class.html">RxBlocProvider</a> and the current BuildContext.</p><p>Let’s see how we can react to the errors from the BloC and show the <a href="https://api.flutter.dev/flutter/material/SnackBar-class.html">SnackBar</a> accordingly.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/pages/home_page.dart#L20"><strong>home_page.dart</strong></a></p><pre><strong>RxBlocListener</strong>&lt;<strong>CounterBlocType</strong>, <strong>String</strong>&gt;(<br>    <strong>state</strong>: (bloc) =&gt; bloc.states.errors,<br>    <strong>listener</strong>: (context, errorMessage) =&gt;<br>        Scaffold.of(context).showSnackBar(<br>            SnackBar(content: Text(errorMessage),<br>        ),<br>)</pre><h3>Conclusion</h3><p><a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a> provides you with a sufficient widget library that takes care of the lifecycle of your reactive BloCs. Since it’s based on the <a href="https://pub.dev/packages/provider">provider</a> package it’s compatible with many great libraries such as <a href="https://pub.dev/packages/auto_route">auto_route</a> and many more.</p><h3>Related articles</h3><ol><li><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a></li><li><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building forms in Flutter</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d9114da473" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473">Introducing flutter_rx_bloc: Part 3</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing rx_bloc: Part 2]]></title>
            <link>https://medium.com/prime-holding-jsc/introducing-rx-bloc-part-2-faf956f2bd99?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf956f2bd99</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 15:46:29 GMT</pubDate>
            <atom:updated>2021-03-02T07:15:55.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OBBgp2Lf1hRCrZGk3tFDQ.png" /></figure><p><strong>The </strong><a href="https://pub.dev/packages/rx_bloc"><strong>rx_bloc</strong></a> is a Dart package that helps to implement the BLoC (Business Logic Component) Design Pattern using the power of the reactive streams. In the previous article, <a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-3cc5f4fff14e"><strong>introducing rx_bloc ecosystem: Part 1</strong></a><strong> </strong>(I recommend that you read it quickly before continuing with this article if you haven’t already)<strong>,</strong> you learned what motivated us to build this package …now it is time to see how it works in action.</p><p>By definition, the BloC layer should contain only the business logic of your app. This means that it should be fully decoupled from the UI layer and should be loosely coupled with the data layer through <strong>Dependency Injection.</strong></p><p>Thus, the <strong>UI layer</strong> communicates with the <strong>BloC</strong> by sending <strong>events</strong> and listens for <strong>state</strong> changes. Let’s see again what the Counter sample we want to build looks like and what the contracts will be:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_rPIHzz26Po%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_rPIHzz26Po&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_rPIHzz26Po%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0f2161a3489c33eeaa2cfa26f05b51/href">https://medium.com/media/1b0f2161a3489c33eeaa2cfa26f05b51/href</a></iframe><h3>Events</h3><p>Users can basically do two things in the Counter sample, they can either increment or decrement the <em>count. </em>To achieve this, we need to create a new file <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L8"><strong>counter_bloc.dart</strong></a> and to define the following <strong>Events</strong> contract<em>.</em></p><pre><em>/// A contract, containing all Counter BloC events</em><br>abstract class <strong>CounterBlocEvents</strong> {<br>  <em>/// Increment the count</em><br>  <strong>void</strong> <strong>increment</strong>();<br><br>  <em>/// Decrement the count</em><br>  <strong>void</strong> <strong>decrement</strong>();<br>}</pre><p>As you can see, all events are just pure methods declared in one abstract class (<strong>CounterBlocEvents</strong>). This way, we can push events to the BloC by simply invoking those methods from the UI layer as follows:</p><pre>RaisedButton(<br>    onPressed: () =&gt; bloc.events.<strong>increment</strong>(),<br>    ...<br>) </pre><h3>States</h3><p>When the user taps on the decrement or increment button, they should see a loading indicator while the API request is being executed. Once the API returns a response, the app should present either the updated count or a user-friendly error message. For this, we need to define the following <strong>States</strong> contract.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L17"><strong>counter_bloc.dart</strong></a></p><pre><em>/// A contract, containing all Counter BloC states</em><br>abstract class <strong>CounterBlocStates</strong> {<br>  <em>/// The count of the Counter</em><br>  <em>///</em><br>  <em>/// It can be controlled by executing<br>  /// [CounterBlocEvents.</em><strong><em>increment</em></strong><em>] and</em><br>  <em>/// [CounterBlocEvents.</em><strong><em>decrement</em></strong><em>]</em><br>  <em>///</em><br>  Stream&lt;int&gt; get <strong>count</strong>;<br><br>  <em>/// Loading state</em><br>  Stream&lt;bool&gt; get <strong>isLoading</strong>;<br><br>  <em>/// User friendly error messages</em><br>  Stream&lt;String&gt; get <strong>errors</strong>;<br>}</pre><p><strong>The same way as with the events</strong>, now you can see that we have declarations for multiple states grouped in one abstract class (<strong>CounterBlocStates</strong>). Depending on your goals, you can either have just one stream with all needed data or you can split it into individual streams. In the latter case, you can apply the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single-responsibility principle</a> or any performance optimizations. We will see how we can take advantage of having multiple states per BloC in a minute.</p><h3>Zero-boilerplate BloC</h3><p>Once we have defined the <strong>states </strong>and <strong>events </strong>contracts, it’s time to implement the actual Counter BloC, where the business logic of the main feature of the app will reside. So let’s create the CounterBloc class in counter_bloc.dart (just after the contracts) as shown below <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L33">counter_bloc.dart</a></p><pre>...<br><strong>@RxBloc</strong>()<br><strong>class</strong> <strong>CounterBloc</strong> <strong>extends</strong> $<strong>CounterBloc</strong> {}</pre><h4>Android Studio Plugin</h4><p>You can create the contracts along with the BloC class by yourself, but this seems to be a tedious task, isn’t it? So, to facilitate this we recommend using the <a href="https://plugins.jetbrains.com/plugin/16165-rxbloc?preview=true">RxBloC Plugin for <strong>Android Studio</strong></a> that helps effectively creating reactive BloCs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l04uaaQ__etAGr0i.png" /></figure><p>By selecting New -&gt; RxBloc Class the plugin will create the following files</p><ul><li>${name}_bloc.dart The file, where the business logic resides (the contracts ( events and states) along with the BloC itself).</li><li>${name}_bloc.rxb.g.dart The file, where the autogenerated boilerplate code ($CounterBloc and CounterBlocType) resides.</li></ul><h4>Generator</h4><p>The plugin creates just the initial state of the BloC. For all further updates, you will need a tool, which will be updating the generated file (${name}_bloc.rxb.g.dart) based on your needs. Here is where the <a href="https://pub.dev/packages/rx_bloc_generator">rx_bloc_generator</a> package helps, as automatically writes all the boring boilerplate code so you can focus on your business logic instead. You just need to add it to your pubspec.yaml file as follows:</p><pre>dev_dependencies:<br>  build_runner:<br>  rx_bloc_generator:^2.0.0</pre><p>Once added to the pubspec.yaml, just run flutter pub get to fetch the newly added dependencies, and then start the generator by executing this command flutter packages pub run build_runner watch --delete-conflicting-outputs.</p><p>So let’s implement the business logic of our <strong>Counter BloC.</strong></p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L33"><strong>counter_bloc.dart</strong></a></p><pre><em>/// A BloC responsible for count calculations</em><br><strong>@RxBloc</strong>()<br><strong>class</strong> <strong>CounterBloc</strong> <strong>extends</strong> $<strong>CounterBloc</strong> {<br>  /// The default constructor injecting a repository through <strong>DI</strong><br>  CounterBloc(<strong>this</strong>._repository);</pre><pre>  /// The repository used for data source communication<br>  <strong>final</strong> CounterRepository _repository;<br><br>  <em>/// Map increment and decrement events to the `count` state</em><br>  <strong>@override</strong><br>  Stream&lt;int&gt; _mapToCountState() =&gt; Rx.<strong>merge</strong>&lt;Result&lt;int&gt;&gt;([<br>            <em>// On increment</em><br>            <strong>_$incrementEvent</strong>.flatMap((_) =&gt;<br>                _repository.<strong>increment</strong>().asResultStream()),<br>            <em>// On decrement</em><br>            <strong>_$decrementEvent</strong>.flatMap((_) =&gt; <br>                _repository.<strong>decrement</strong>().asResultStream()),<br>        ])<br>        <em>// This automatically handles the error and loading state.</em><br>        .<strong>setResultStateHandler</strong>(<strong>this</strong>)<br>        <em>// Provide &quot;success&quot; response only.</em><br>        .whereSuccess()<br>        <em>//emit 0 as an initial value</em><br>        .startWith(0);<br>    ...<br>}</pre><p>As you can see, by extending <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.rxb.g.dart#L20">$</a><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.rxb.g.dart#L20"><strong>CounterBloc</strong></a><strong>, </strong>we must implement Stream&lt;int&gt; <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L42">_mapToCountState()</a> , which is the method responsible for the events-to-state business logic. Furthermore, we have <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L44">_$incrementEvent</a> and <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L47">_$decrementEvent</a>, which are the <a href="https://pub.dev/documentation/rxdart/latest/rx_subjects/rx_subjects-library.html"><strong>subjects</strong></a> where the events will flow when <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L10"><strong>increment</strong></a><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L10">()</a> and <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L13"><strong>decrement</strong></a><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L13">()</a> methods are invoked from the UI Layer.</p><p>In the code above we declare that as soon as the user taps on the increment or decrement button, an API call will be executed. Since both <strong>_$incrementEvent </strong>and <strong>_$decrementEvent </strong>are grouped in one stream by the <a href="https://pub.dev/documentation/rxdart/latest/rx/Rx/merge.html">merge</a> operator, the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/Result-class.html"><strong>result</strong></a> of their API calls allows us to register our BloC as a <strong>state handler. </strong>We then extract only the “success” result and finally put an initial value of 0<strong>.</strong></p><h4>State Handlers</h4><p>Most of the time when building mobile applications we have to communicate with external APIs, which means that we need to take care of:</p><ol><li>Error handling</li><li>Loading state</li></ol><p>Fortunately, <a href="https://pub.dev/packages/rx_bloc"><strong><em>rx_bloc</em></strong></a> has built-in tools that can help us with this.</p><p>As you can see, we set the current BloC as a <a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L51"><strong>state handler</strong></a> to a particular <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/Result-class.html"><strong>Result</strong></a> stream and then we get only the success state. But wait for a second, what about the <strong>error</strong> and <strong>loading</strong> handling? By using <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/HandleByRxBlocBase/setResultStateHandler.html"><strong>setResultStateHandler</strong></a>, both are handled by the BloC, as all errors are dispatched to the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/errorState.html"><strong>errorState</strong></a><strong> </strong><a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a> and all loading activities are dispatched to the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/loadingState.html"><strong>loadingState</strong></a><strong> </strong><a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a><strong>.</strong></p><p>The advantage of this approach is that you have one <strong>central</strong> place (<a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a>) for all loading activities and one <strong>central</strong> place (<a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a>) for all errors that happen within the Counter BloC. In addition, if you need to execute API calls in a couple of <em>event-to-state</em> <strong>mappers</strong> within one BloC, the app would have to either show a loading indicator for all of them or handle all errors. In this case, the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/errorState.html"><strong>errorState</strong></a><strong> </strong><a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a> and the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/loadingState.html"><strong>loadingState</strong></a><strong> </strong><a href="https://pub.dev/documentation/rxdart/latest/rx_streams/rx_streams-library.html">stream</a> would be particularly beneficial.</p><p>So far so good, going back to the implementation, the <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/errorState.html"><strong>errorState</strong></a><strong> </strong>and <a href="https://pub.dev/documentation/rx_bloc/latest/rx_bloc/RxBlocBase/loadingState.html"><strong>loadingState</strong></a> are not exposed yet, so we need to take care of them by simply writing mappers as follows:</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/a1854040f1d693af5304bce7a5c2fa68c5809ecf/examples/counter/lib/bloc/counter_bloc.dart#L57"><strong>counter_bloc.dart</strong></a></p><pre><strong>@RxBloc</strong>()<br><strong>class</strong> <strong>CounterBloc</strong> <strong>extends</strong> $<strong>CounterBloc</strong> {<br>  ...<br>  <strong>@override</strong><br>  Stream&lt;String&gt; <strong>_mapToErrorsState</strong>() =&gt;<br>      <strong>errorState</strong>.map((Exception error) =&gt; error.toString());<br><br>  <strong>@override</strong><br>  Stream&lt;bool&gt; <strong>_mapToIsLoadingState</strong>() =&gt; <strong>loadingState</strong>;<br>}</pre><p>The advantage of manually exposing these states is that you have total control over your BloC states. For example, you can map an exception to a user-friendly error message.</p><h3>Put it all together</h3><pre><em>/// This BloC and its event and state contracts usually</em><br><em>/// reside in counter_bloc.dart</em><br><br><em>/// A contract class containing all events.</em><br>abstract class <strong>CounterBlocEvents</strong> {<br>  <em>/// Increment the count</em><br>  <strong>void</strong> <strong>increment</strong>();<br><br>  <em>/// Decrement the count</em><br>  <strong>void</strong> <strong>decrement</strong>();<br>}<br><br><em>/// A contract class containing all states for our multi-state BloC.</em><br><strong>abstract</strong> <strong>class</strong> <strong>CounterBlocStates</strong> {<br>  <em>/// The count of the Counter</em><br>  <em>///</em><br>  <em>/// It can be controlled by executing <br>  /// [CounterBlocEvents.increment] and</em><br>  <em>/// [CounterBlocEvents.decrement]</em><br>  <em>///</em><br>  Stream&lt;int&gt; <strong>get</strong> <strong>count</strong>;<br><br>  <em>/// Loading state</em><br>  Stream&lt;bool&gt; <strong>get</strong> <strong>isLoading</strong>;<br><br>  <em>/// Error messages</em><br>  Stream&lt;String&gt; <strong>get</strong> <strong>errors</strong>;<br>}<br><br><em>/// A BloC responsible for count calculations</em><br><strong>@RxBloc</strong>()<br><strong>class</strong> <strong>CounterBloc</strong> <strong>extends</strong> $<strong>CounterBloc</strong> {<br>  <em>/// Default constructor</em><br>  CounterBloc(<strong>this</strong>._repository);<br><br>  <strong>final</strong> CounterRepository _repository;<br><br>  <em>/// Map increment and decrement events to `count` state</em><br>  <strong>@override</strong><br>  Stream&lt;int&gt; <strong>_mapToCountState</strong>() =&gt; Rx.merge&lt;Result&lt;int&gt;&gt;([<br>            <em>// On increment.</em><br>            _$<strong>incrementEvent</strong>.flatMap((_) =&gt; <br>                _repository.<strong>increment</strong>().asResultStream()),<br>            <em>// On decrement.</em><br>            _$<strong>decrementEvent</strong>.flatMap((_) =&gt; <br>                _repository.<strong>decrement</strong>().asResultStream()),<br>       ])<br>       <em>// This automatically handles the error and loading state.</em><br>       .<strong>setResultStateHandler</strong>(<strong>this</strong>)<br>       <em>// Provide success response only.</em><br>       .whereSuccess()<br>       <em>//emit 0 as an initial value</em><br>       .startWith(0);<br><br>  <strong>@override</strong><br>  Stream&lt;String&gt; <strong>_mapToErrorsState</strong>() =&gt;<br>      <strong>errorState</strong>.map((Exception error) =&gt; error.toString());<br><br>  <strong>@override</strong><br>  Stream&lt;bool&gt; <strong>_mapToIsLoadingState</strong>() =&gt; <strong>loadingState</strong>;<br>}</pre><h3>Unit tests</h3><p>One of the advantages of having a clean business layer is that it is unit-testable, right?</p><p>Let’s see how the <a href="https://pub.dev/packages/rx_bloc_test"><strong>rx_bloc_test</strong></a><strong> </strong>package<strong> </strong>can reduce the development time for implementing unit tests and also make them easy to read and maintain.</p><pre>rxBlocTest&lt;<strong>CounterBloc</strong>, <strong>int</strong>&gt;(<br>  &#39;Incrementing value&#39;,<br>  <strong>build</strong>: () async =&gt; CounterBloc(<strong>CounterRepositoryMock</strong>()), <br>  <strong>state</strong>: (bloc) =&gt; bloc.states.count,<br>  <strong>act</strong>: (bloc) async =&gt; bloc.events.increment(),<br>  <strong>expect</strong>: [1],<br>)</pre><p>You can see that we specify the BloC type along with the type of state we want to test. We then create an <strong>instance</strong> of the BloC, specify the exact <strong>state</strong>, send some <strong>events</strong> to the BloC and finally <strong>assert</strong> that the actual result is the one we expect it to be.</p><p>For more information and examples check the <a href="https://github.com/Prime-Holding/rx_bloc/tree/master/packages/rx_bloc_test"><strong>package</strong></a> and the <a href="https://github.com/Prime-Holding/rx_bloc/tree/master/examples/favorites_advanced/rx_bloc_favorites_advanced/test"><strong>samples</strong></a><strong>.</strong></p><h3>Conclusion</h3><p>Using<strong> </strong><a href="https://pub.dev/packages/rx_bloc"><strong>rx_bloc</strong></a> in combination with<strong> </strong><a href="https://pub.dev/packages/rx_bloc_generator"><strong>rx_bloc _generator</strong></a> makes the BloCs clean, easy to maintain, zero-boilerplate, and completely unit-testable. With <a href="https://pub.dev/packages/rx_bloc_test"><strong>rx_bloc_test</strong></a> we can ensure that our BloCs work as expected. But now the question is how do we expose our reactive BloCs to the UI layer? Since this is a fairly large topic, it deserves to be considered separately, so if you’re interested, check out the next article: <a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473"><strong>Introducing flutter_rx_bloc: Part 3</strong></a></p><h3>Related articles</h3><ol><li><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a></li><li><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building forms in Flutter</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf956f2bd99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-part-2-faf956f2bd99">Introducing rx_bloc: Part 2</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing rx_bloc ecosystem: Part 1]]></title>
            <link>https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc5f4fff14e</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 15:46:15 GMT</pubDate>
            <atom:updated>2021-03-23T13:48:47.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing rx_bloc ecosystem - Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtXan2Z0cidxAxX-8gpKBA.png" /></figure><h3>Intro</h3><p>State management is and will continue to be one of the hottest topics in the Flutter community. Even though Flutter comes with built-in <strong>Stateful Widgets</strong>, this is not enough for building an app that follows the <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a> principles. If you want the app you are building to be <strong>robust, scalable, and maintainable, you </strong>need to somehow separate the <strong>data layer</strong> from the <strong>business layer</strong> and then the <strong>business layer </strong>from the <strong>UI layer</strong>, right?</p><p>Based on your engineering experience and the needs of your project, you have the freedom to choose among a variety of state management solutions such as <a href="https://pub.dev/packages/rx_bloc">rx_bloc</a>, <a href="https://pub.dev/packages/redux">redux</a>, <a href="https://pub.dev/packages/bloc">bloc</a>, <a href="https://pub.dev/packages/mobx">mobx</a>, and many more. As decision-makers and mobile architects, we need to be aware of all <strong>pros</strong> and <strong>cons</strong> of the solutions so we can pick the right tool for the job.</p><p>With all that being said, let’s see what motivated us to build the <strong>rx_bloc</strong> ecosystem and what it includes so you can decide whether this is the right tool for your project.</p><h3>Motivation</h3><p>If you are working on a complex project you might be challenged to build a highly interactive UI or a heavy business logic in a combination with the consumption of various data sources such as REST APIs, Web Socket, Secured Storage, Shared Preferences, etc. To achieve this, you might need a tool that facilitates your work during product development.</p><p>Fortunately, in Flutter there is <a href="https://pub.dev/packages/rxdart"><strong>rxdart</strong></a>, which brings the Dart <strong>Streams</strong> and <strong>Stream</strong>Controllers to an entirely new level by adding functionality from the reactive extensions specification on top of them. In fact, today we can see reactive programming everywhere. In <strong>Front-end</strong> web development there is <a href="https://github.com/ReactiveX/rxjs">rx.js</a>, which is the core of <a href="https://angular.io/">Angular</a>. In <strong>Back-end</strong> Development we see libraries such as <a href="https://projectreactor.io/">Project Reactor</a>, in the native <strong>iOS </strong>development there is <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>, and <a href="https://github.com/ReactiveX/RxJava">RxJava</a>/<a href="https://github.com/ReactiveX/RxKotlin">RxKotlin</a> we see in <strong>Android</strong> development.</p><p>So, since rxdart boosts async programming, we thought about why not combine it with the well-known BloC pattern and develop a set of packages that will help developers build robust, scalable, and maintainable solutions faster and more easily.</p><h3>The result</h3><p>Thus, we developed the following set of tools:</p><ul><li><a href="https://pub.dev/packages/rx_bloc"><strong>rx_bloc</strong></a> that helps to implement the BLoC (Business Logic Component) Design Pattern using the power of the reactive streams.</li><li><a href="https://pub.dev/packages/flutter_rx_bloc"><strong>flutter_rx_bloc</strong></a><strong> </strong>that<strong> </strong>exposes your reactive BloCs to the UI Layer.</li><li><a href="https://pub.dev/packages/rx_bloc_test"><strong>rx_bloc_test</strong></a> that facilitates implementing the unit tests for your BloCs</li><li><a href="https://pub.dev/packages/rx_bloc_generator"><strong>rx_bloc_generator</strong></a><strong> </strong>that boosts development efficiency by making your BloCs zero-boilerplate.</li><li><a href="https://pub.dev/packages/rx_bloc_list"><strong>rx_bloc_list</strong></a><strong> </strong>that facilitates implementing infinity scroll and pull-to-refresh features with minimal setup</li><li><a href="https://plugins.jetbrains.com/plugin/16165-rxbloc"><strong>Android Studio Plugin</strong></a><strong> </strong>for effectively creating reactive BloCs.</li></ul><h3>Sample</h3><p>The most efficient way of getting familiar with something new as quickly as possible is to see how it works in action, right? So check out the video below to see what the Counter app we want to build looks like.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_rPIHzz26Po%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_rPIHzz26Po&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_rPIHzz26Po%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0f2161a3489c33eeaa2cfa26f05b51/href">https://medium.com/media/1b0f2161a3489c33eeaa2cfa26f05b51/href</a></iframe><p>In the following articles we will see how you can build a more advanced version of the world-famous <a href="https://github.com/Prime-Holding/rx_bloc/tree/develop/examples/counter"><strong>Counter</strong></a><strong> </strong>sample which will be more challenging and interesting as it will be communicating with an API and it will be handling the following states:</p><ul><li><strong>Handling error state</strong><br>As soon as users reach the min/max possible count they will be presented with an informative snack bar.</li><li><strong>Handling loading state<br></strong>While the API request is being executed, the action buttons will be disabled and a loading indicator will appear so that the user will know that something is happening.</li><li><strong>Handling success state<br></strong>The count will be updated only if the API returns a “success” response. This means that the widget responsible for showing the counter will not be rebuilt in case of loading or error.</li></ul><h3>What’s next?</h3><ul><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99"><strong>Introducing rx_bloc: Part 2</strong></a><strong><br></strong>Dart package that helps to implement the BLoC (Business Logic Component) Design Pattern using the power of the reactive streams.</li><li><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473"><strong>Introducing flutter_rx_bloc: Part 3</strong></a><strong><br></strong>Set of Flutter Widgets that exposes your reactive BloCs to the UI Layer.</li></ul><h3>Related articles</h3><ol><li><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a></li><li><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building forms in Flutter</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc5f4fff14e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">Introducing rx_bloc ecosystem: Part 1</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building complex apps in Flutter through the power of reactive programming]]></title>
            <link>https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a38fbc0cde</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Fri, 04 Dec 2020 14:13:04 GMT</pubDate>
            <atom:updated>2021-02-19T14:36:27.899Z</atom:updated>
            <content:encoded><![CDATA[<p>Developing complex apps that meet user expectations while consuming a fragmented API can be a challenge these days.</p><p>Let’s look at the following challenges we might face while working on real-world applications.</p><ol><li>Inter-feature communication</li><li>API requests optimization without compromising on the best UX</li><li>Building a super responsive app</li><li>Implementing functionality that can work in various scenarios</li><li>Building an app that can handle millions of mutable records</li></ol><h3>Inter-feature communication</h3><p>You may work on an app that has various features that need to communicate with each other. Imagine that your app needs to show a list of entities that the user can mark as favorites or mutate in any other way.</p><p>Let’s see what this would look like, assuming we need to show some cute puppies…. Well because why not, right?</p><p>Users only see two lists of puppies, but we as software engineers see much more.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F__bFdDvVyRk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D__bFdDvVyRk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F__bFdDvVyRk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a8e3f103bfaccff5c5193bdcab05ed/href">https://medium.com/media/76a8e3f103bfaccff5c5193bdcab05ed/href</a></iframe><p>Let’s assume that the state management we’ve chosen for this particular project is BloC (Business Logic Component)…so we need to implement BloCs such as <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/favorites/blocs/favorite_puppies_bloc.dart">FavoritesBloc</a>, <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/search/blocs/puppy_list_bloc.dart">SearchBloc</a>, <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppies_extra_details_bloc.dart">ExtraDetailsBloc</a>, <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart">PuppyManageBloc</a>, etc. When a puppy gets updated, both lists (search and favorites) need to be updated accordingly.</p><p>We could approach the <strong>inter-feature</strong> communication challenge by setting up dependencies between the BloCs. BloC A could be dependent on BloC B, Bloc C on BloC B, etc, but we might end up with circular dependencies that are difficult to manage.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/base/common_blocs/coordinator_bloc.dart"><strong>Coordinator</strong> <strong>pattern</strong></a><strong> </strong>to the rescue!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhJGZTnwz2lzOtKom-SiJQ.jpeg" /></figure><p>We now have a central place for inter-bloc communication, so there is no need to deal with a complex dependency graph. Each BloC emits events to the <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/base/common_blocs/coordinator_bloc.dart"><strong>CoordinatorBloc</strong></a><strong> </strong>and each BloC can <strong>listen</strong> and <strong>react</strong> accordingly.</p><h3>API request optimization without compromising on the best UX</h3><p>Building the API with microservice architecture makes it scalable by its nature but sometimes the endpoints become very fragmented and in the mobile app we need to handle this somehow.</p><p>Imagine that with the first API call, the app can fetch a list of puppies, but then users need to be provided with some additional details that need to be loaded later, as shown below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fo22eky697Hw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Do22eky697Hw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fo22eky697Hw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c848e1f45795927d4b2fa2b00ff185/href">https://medium.com/media/87c848e1f45795927d4b2fa2b00ff185/href</a></iframe><ol><li>The app needs to fetch the additional details one by one when the users scroll slowly</li><li>The app needs to collect all visible entities and get these additional details with just one API call when the user scrolls fast and then suddenly stops</li></ol><p><strong>Now seems like the right time to see some code, right?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLmNwrBhejkK9EFP504%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmemecandy-LmNwrBhejkK9EFP504&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FLmNwrBhejkK9EFP504%2Fgiphy.gif%3Fcid%3D790b7611d61ad1e0a8a2e968ec437ae05ac438c714625941%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f0a50f21fe94b914f061bece2d70fd/href">https://medium.com/media/51f0a50f21fe94b914f061bece2d70fd/href</a></iframe><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppies_extra_details_bloc.dart">puppies_extra_details.dart</a></p><pre>@RxBloc()<br>class <strong>PuppiesExtraDetailsBloc</strong> extends $PuppiesExtraDetailsBloc {</pre><pre>PuppiesExtraDetailsBloc(...) {<br>    // This event gets emited when a puppy entity becomes visible on the screen.<br>    _$<strong>fetchExtraDetailsEvent</strong><br>        // <em>Fetch extra details collected in 100 millisecond buckets.</em><br>        .<strong>fetchExtraDetails</strong>(repository, coordinatorBloc)<br>        // Bind the result (List&lt;Puppies&gt;) to the local state<br>        .<strong>bind</strong>(_lastFetchedPuppies)<br>        // Always make sure your subscriptions are disposed of!<br>        .<strong>disposedBy</strong>(_compositeSubscription);<br>  }<br>....<br>}</pre><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppies_extra_details_bloc_extensions.dart">puppies_extra_details_bloc_extensions.dart</a></p><pre><br>extension _StreamFetchExtraDetails on Stream&lt;Puppy&gt; {</pre><pre><em>/// Fetch extra details collected in 100 millisecond buckets.<br>  </em>Stream&lt;List&lt;Puppy&gt;&gt; <strong>fetchExtraDetails</strong>(...) =&gt;<br>      // Collect puppies in <em>100 milliseconds buckets</em><br>      <strong>bufferTime</strong>(const Duration(milliseconds: 100))<br>          // Get the puppies that still have no extra details.<br>          .<strong>map</strong>((puppies) =&gt; puppies.whereNoExtraDetails())<br>          // Only execute API call if needed.<br>          .<strong>where</strong>((puppies) =&gt; puppies.isNotEmpty)<br>          // Get all extra details from the API<br>         .<strong>flatMap</strong>(<br>              (value) =&gt; repository.fetchFullEntities(value.ids).asStream())<br>          // Notify the coordination BloC<br>         .<strong>doOnData</strong>((puppies) =&gt;<br>    coordinatorBloc.events.puppiesWithExtraDetailsFetched(puppies));<br>}</pre><p>The UI layer can tell the business layer which items are currently on the screen using <a href="https://pub.dev/packages/visibility_detector">this package</a>. Then the business logic layer collects all entities that the UI layer has reported in 100 milliseconds buckets. This means that the business layer will be collecting entities and waiting 100 ms before fetching the actual extra details from the API. With this, we provide the best UX and at the same time, the API is not flooded with too many requests.</p><h3>Building a super responsive app</h3><p>Nowadays users have very high expectations. Usually, the user needs to wait while the API call is being executed (login form, fetching data, etc.) but there are multiple scenarios in which the app needs to present the intended result to the user immediately while the API call is being executed in the background. A perfect example of this is the <strong><em>like</em></strong> functionality in social networks … or marking a puppy as a favorite.</p><p>The challenge here is to handle the error case somehow, right?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYHjKfokqR74%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYHjKfokqR74&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYHjKfokqR74%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/48cafcbdd8b03244515370beb35b7dcd/href">https://medium.com/media/48cafcbdd8b03244515370beb35b7dcd/href</a></iframe><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc_extensions.dart">puppy_manage_bloc_extensions.dart</a></p><pre>...<br>markPuppyAsFavorite(...) =&gt; <br>   throttleTime(const Duration(milliseconds: 200))<br>    .switchMap&lt;Result&lt;Puppy&gt;&gt;((args) async* {<br>      yield Result.loading();<br>      // Emit an event with the <strong>copied instance</strong> of the entity<br>      // so that the UI can update <strong>immediately.</strong><br>      yield Result.success(<br>        args.puppy.copyWith(isFavorite: args.isFavorite),<br>      );<br><br>      yield Result.loading();<br>      try {<br>        final updatedPuppy = await puppiesRepository<br>            .favoritePuppy(args.puppy, isFavorite: args.isFavorite);<br><br>        yield Result.success(<br>          updatedPuppy.copyWith(<br>            displayBreedCharacteristics:<br>                args.puppy.displayBreedCharacteristics,<br>            displayName: args.puppy.displayName,<br>          ),<br>        );<br>      } catch (error) {<br>        // In case of an error we <strong>rollback</strong> the puppy to<br>        // the <strong>previous state</strong> and notify the UI layer for the error<br>        bloc._favoritePuppyError.sink.add(error);<br>        yield Result.success(args.puppy);<br>      }<br>    })<br>...</pre><p>Here we can see that we emit a copied version of the entity to the UI so that users can immediately see the intended result. In case the API request fails though, we rollback the original object and display an error message.</p><h3>Implementing functionality that can work in various scenarios</h3><p>Even though the listing looks very simple, let’s see what cases we need to cover</p><ul><li>Presenting various loading indicators based on user actions</li><li>Having basic functionalities, such as pull-to-refresh or an error widget, working both in the puppy list and in search mode as well</li><li>Updating the global counter based on user actions coming from different places</li></ul><p>As I mentioned earlier, from the user perspective things are simple and they have to be that way…so we have to make an extra effort to handle all those cases, right?</p><p>Let’s see how reactive programming can help us achieve our goals.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/01b358faf93fbd952032ac9a8cb815fad36f9fa5/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/search/blocs/puppy_list_bloc_extensions.dart#L39">puppy_list_bloc_extensions.dart</a></p><pre><em>/// Use [filterPuppies] and [reloadFavoritePuppies] as<br>/// a reload trigger.<br></em>Stream&lt;_ReloadData&gt; _reloadTrigger() =&gt; Rx.<em>merge</em>([<br>      _$filterPuppiesEvent.distinct().map((query) =&gt; _ReloadData(<br>            silently: false,<br>            query: query,<br>          )),<br>      _$reloadFavoritePuppiesEvent.map((silently) =&gt; _ReloadData(<br>            silently: silently,<br>            query: _$filterPuppiesEvent.value,<br>          )),<br>    ]);</pre><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/01b358faf93fbd952032ac9a8cb815fad36f9fa5/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/search/blocs/puppy_list_bloc_extensions.dart#L8">puppy_list_bloc_extension.dart</a></p><pre>Stream&lt;Result&lt;List&lt;Puppy&gt;&gt;&gt; fetchPuppies(PuppiesRepository repository) =&gt;<br>      debounceTime(const Duration(milliseconds: 600)).switchMap(<br>        (reloadData) =&gt; repository<br>            .getPuppies(query: reloadData.query)<br>            .asResultStream()<br>            // skip the loading event if silently is true<br>            .skip(reloadData.silently ? 1 : 0),<br>      );</pre><p>As you can see, we utilize the <a href="https://pub.dev/documentation/rxdart/latest/rx/Rx/merge.html">merge</a> operator so that we can combine various user actions into one trigger, then we ensure that the API request is being executed when the user stops typing for at least 600ms using the <a href="https://pub.dev/documentation/rxdart/latest/rx/DebounceExtensions/debounce.html">debounce</a> operator, and finally, we request from the API the list of puppies using the <a href="https://pub.dev/documentation/rxdart/latest/rx/SwitchMapExtension/switchMap.html">switchMap</a> operator. In case something goes wrong, we still have the conditions to retry the API call when the user presses the retry button.</p><p>We mentioned in the beginning that the <strong>coordinator pattern</strong> solves some design challenges, but let’s see if it can help us update the counter.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart">puppy_manage_bloc.dart</a></p><pre>@RxBloc()<br>class PuppyManageBloc extends $PuppyManageBloc {<br>  PuppyManageBloc(...) {<br>    _$markAsFavoriteEvent<br>        // Mark a puppy as soon as the UI sends an event.<br>        .<strong>markPuppyAsFavorite</strong>(puppiesRepository, this)<br>        // Notify<strong> </strong>the<strong> coordinator</strong> BloC with the updated puppy.<br>        .doOnData((puppy) =&gt; coordinatorBloc.<strong>events.puppyUpdated</strong>(puppy))<br>        ...<br>  }<br>}</pre><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/favorites/blocs/favorite_puppies_bloc.dart">favorite_puppies_bloc.dart</a></p><pre>abstract class FavoritePuppiesEvents {<br>  @RxBlocEvent(type: RxBlocEventType.behaviour, seed: false)<br>  void reloadFavoritePuppies({bool silently});<br>}<br><br>abstract class FavoritePuppiesStates {<br>  @RxBlocIgnoreState()<br>  Stream&lt;Result&lt;List&lt;Puppy&gt;&gt;&gt; get favoritePuppies;<br><br>  Stream&lt;int&gt; get count;<br>}</pre><pre>@RxBloc()<br>class FavoritePuppiesBloc extends $FavoritePuppiesBloc {<br>  FavoritePuppiesBloc(...) {<br>    coordinatorBloc.states.<strong>onPuppiesUpdated</strong><br>        .<strong>updateFavoritePuppies</strong>(_favoritePuppies)<br>        .disposedBy(_compositeSubscription);<br>  }</pre><pre>  @override<br>  Stream&lt;int&gt; _mapToCountState() =&gt; _favoritePuppies.mapToCount();<br>}</pre><p>You can see that the BloC responsible for updating the puppy emits an event to the <strong>coordinator BloC, </strong>after which the BloC that is responsible for marking the puppies as favorites listens to this change and updates the list accordingly. Since <a href="https://pub.dev/packages/flutter_rx_bloc"><strong>rx_bloc</strong></a> supports <a href="https://github.com/Prime-Holding/rx_bloc/tree/master/packages/flutter_rx_bloc#faq">multiple states per BloC</a>, we can expose the state <a href="https://github.com/Prime-Holding/rx_bloc/blob/01b358faf93fbd952032ac9a8cb815fad36f9fa5/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/favorites/blocs/favorite_puppies_bloc.dart#L23"><strong>FavoritePuppiesStates</strong>.<strong>count</strong></a>, which tells Flutter that there is a state change and the UI needs to be updated accordingly. This is also a performance optimization, as we rebuild only a small portion of the widget tree, which keeps our app <strong>fast</strong> and <strong>responsive</strong>.</p><h3>Building an app that can handle millions of mutable records</h3><p>As we know, Flutter is very fast, but what if we need to push this technology to its limits? What if we need to handle millions of records and still want the app to be fast and responsive? Let’s see how we can achieve this.</p><p><strong>Option 1</strong></p><p>We can create instances of PuppyManage BloC as the user scrolls through the list. This will ensure that the extra details are fetched only when needed and the app still meets the requirements for the API requests mentioned above.</p><p>So far so good, but here we would have one big problem that would cause huge performance issues. When the user scrolls quickly, the app has to create hundreds of instances and at the same time, the UI has to create subscriptions for each BloC state separately so our app will become very slow.</p><p><strong>Option 2</strong></p><p>Having only one instance of each BloC type, such as <strong>search</strong>, <strong>favorites,</strong> and <strong>puppy management.</strong> Let’s see what this would look like.</p><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/favorites/blocs/favorite_puppies_bloc.dart">favorite_puppies_bloc.dart</a></p><pre>@RxBloc()<br>class FavoritePuppiesBloc extends $FavoritePuppiesBloc {<br>  FavoritePuppiesBloc(...) {<br><br>    coordinatorBloc.states.<strong>onPuppiesUpdated</strong><br>        .updateFavoritePuppies(<strong>_favoritePuppies</strong>)<br>        .disposedBy(_compositeSubscription);<br>  }<br><br>  final <strong>_favoritePuppies</strong> =<br>      BehaviorSubject.seeded(Result&lt;List&lt;Puppy&gt;&gt;.success([]));<br>  <br>  ...<br>}</pre><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/search/blocs/puppy_list_bloc.dart">puppy_list_bloc.dart</a></p><pre>@RxBloc()<br>class PuppyListBloc extends $PuppyListBloc {<br>  PuppyListBloc(...) {<br>    coordinatorBloc.states.<strong>onPuppiesUpdated</strong><br>        .updatePuppies(<strong>_puppies</strong>)<br>        .disposedBy(_compositeSubscription);<br>  }<br><br>  final <strong>_puppies</strong> = BehaviorSubject.seeded(<br>      Result&lt;List&lt;Puppy&gt;&gt;.success([])<br>  );<br>}</pre><p><a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart">puppy_manage_bloc.dart</a></p><pre>@RxBloc()<br>class PuppyManageBloc extends $PuppyManageBloc {<br>  PuppyManageBloc(...) {<br>    _$markAsFavoriteEvent<br>        .<strong>markPuppyAsFavorite</strong>(puppiesRepository, this)<br>        .doOnData((puppy) =&gt; coordinatorBloc.<strong>events.puppyUpdated</strong>(puppy))<br>....<br>}</pre><p>You can see that both the search and the favorite list have their own state, which is updated according to the puppy updates sent from the <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/feature_puppy/blocs/puppy_manage_bloc.dart"><strong>ManagePuppy</strong></a> BloC through the <a href="https://github.com/Prime-Holding/rx_bloc/blob/master/examples/favorites_advanced/rx_bloc_favorites_advanced/lib/base/common_blocs/coordinator_bloc.dart">C<strong>oordinatorBloc</strong></a>. This works not only for marking a puppy as a favorite but also for <strong>fetching</strong> <strong>extra</strong> details. But wait for a second…does this mean that given that we have millions of records, the BloC has to find the one that is being updated, replace it, and then tell the UI that there is a state change? And the app is still working flawlessly? As I mentioned earlier Flutter is very fast so yes, the app still works smoothly.</p><h3>Architecture: the big picture</h3><p><a href="https://pub.dev/packages/rx_bloc">rx_bloc</a> makes it easy to implement the BLoC design pattern using the power of reactive streams.</p><p>Following the best practices for building robust mobile applications the architecture below can be used along with the BloC layer.</p><p>This package is built to work with <a href="https://pub.dev/packages/flutter_rx_bloc">flutter_rx_bloc</a>, <a href="https://pub.dev/packages/rx_bloc_generator">rx_bloc_generator</a>, and <a href="https://pub.dev/packages/rx_bloc_test">rx_bloc_test</a>.</p><p>Read <a href="https://link.medium.com/QX4T10DQtdb">Introducing rx_bloc ecosystem – Part 1</a> to learn how to use these packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Irqq0jpwtDta9W1Q6diZwA.jpeg" /></figure><h3>Conclusion</h3><p>Building apps with <a href="https://pub.dev/packages/rxdart">reactive programming</a> along with a sophisticated architecture is really beneficial. The apps become more <a href="https://pub.dev/packages/rx_bloc_test">robust</a>,<a href="https://pub.dev/packages/flutter_rx_bloc"> scalable</a>, and <a href="https://pub.dev/packages/rx_bloc">maintainable</a>.</p><p>Investing in neat architecture before starting a new project always pays off in the long run.</p><h3>Related articles</h3><ol><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-ecosystem-part-1-3cc5f4fff14e">Introducing rx_bloc ecosystem — Part 1</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-rx-bloc-a-dart-package-that-helps-implementing-the-bloc-design-pattern-faf956f2bd99">Introducing rx_bloc: Part 2</a></li><li><a href="https://medium.com/prime-holding-jsc/introducing-flutter-rx-bloc-part-3-69d9114da473">Introducing flutter_rx_bloc: Part 3</a></li><li><a href="https://medium.com/prime-holding-jsc/building-forms-in-flutter-454b8d65f48">Building forms in Flutter</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a38fbc0cde" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/building-complex-apps-in-flutter-with-the-power-of-reactive-programming-54a38fbc0cde">Building complex apps in Flutter through the power of reactive programming</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common architectural design pattern for iOS and Android applications]]></title>
            <link>https://medium.com/prime-holding-jsc/common-architectural-design-pattern-for-ios-and-android-applications-f02794cce4d4?source=rss-482c0f146cec------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02794cce4d4</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[native-app]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Georgi Stanev]]></dc:creator>
            <pubDate>Fri, 05 Jul 2019 20:40:58 GMT</pubDate>
            <atom:updated>2020-12-04T14:35:11.124Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we always aim to write concise, maintainable, and scalable code. When the project grows, new developers are joining the team, it becomes more and more difficult to stay close to the <em>state of the art</em>. In order to make our lives easier we strive to apply the best practices, but what happens if you need to work on the same project on both dominating mobile OS (Android &amp; iOS)? What if in those you have a completely different code base, in terms of architectural design patterns, used programming paradigm, etc?</p><p>We at <a href="https://primeholding.com/">Prime Holding</a> also faced the above-mentioned challenges so we had to come up with a streamlined and standardized way to do our jobs. And this is exactly what we did. We adopted an end-to-end solution to address these problems — a clearly defined set of rules to guide the flow of the application components. We based our solution on the MVVM architecture with the sole purpose of improving communication between components. Views pass data to view models only through input methods (as defined in an input interface), consume data only through output( utilized as observables defined in output interface), and receive the instance of the view model as a ViewModelType interface. View models tend to get bulky quickly, so this is solved by breaking down the view model into a few smaller view models and providing them through view model composition. And to make the load even lighter on our developers, we introduced templates to be integrated into the respective IDEs.</p><p>Firstly we had to choose among the most popular architectural design patterns for building native mobile applications, such as MVC, MVP, MVVM, MVI, and Viper. After weighing our options we decided that the most suitable pattern would be MVVM, as it provides enough separation of concerns, flexibility, and simplicity at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*wLr3pLpQ_1YFlTgxwNizBA.jpeg" /></figure><blockquote>The Model-View-ViewModel (MVVM) pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI). Maintaining a clean separation between application logic and the UI helps to address numerous development issues and can make an application easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of an app</blockquote><ul><li><a href="https://github.com/StanevPrime/PrimeHoldingAndroidArchitecture">https://github.com/StanevPrime/PrimeHoldingAndroidArchitecture</a></li><li><a href="https://github.com/StanevPrime/PrimeHoldingiOSArchitecture">https://github.com/StanevPrime/PrimeHoldingiOSArchitecture</a></li></ul><p>Secondly, we had to build our templates integrated right into the IDEs, so that we can create all architectural components with ease.</p><ul><li><a href="https://github.com/StanevPrime/PrimeHoldingAndroidTemplates">https://github.com/StanevPrime/PrimeHoldingAndroidTemplates</a></li><li><a href="https://github.com/StanevPrime/PrimeHoldingiOSTemplates">https://github.com/StanevPrime/PrimeHoldingiOSTemplates</a></li></ul><p>In order to make the concept clearer, let’s dive into all architectural layers, describing each of them in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*LAccq9YG7Y7xiC4iXWrVaQ.jpeg" /></figure><h3>ViewController/View</h3><p>A ViewController or a View, with their layout, represents the view layer. The role of the view in this pattern is to:</p><ul><li>Define the structure, layout, and appearance of what the user sees on the screen</li><li>Observe (or subscribe to) ViewModel outputs (<a href="https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#driver">drivers</a>/<a href="https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md#observables-aka-sequences">observables</a>) to get data in order to update UI elements accordingly</li><li>Pass user actions to the ViewModel via its input methods.</li></ul><p><a href="https://github.com/StanevPrime/PrimeHoldingiOSTemplatesSample/blob/master/Test1/ViewControllers/DetailsViewController.swift">ViewController example</a></p><h3>ViewModel</h3><p>The view model is an abstraction of the view exposing outputs (observables) and inputs (methods). Each ViewModel should encapsulate the business logic in a way that makes it easy to be reused across the entire app. The following rules have to be considered when a ViewModel is being implemented:</p><ul><li>It should never reference a view.</li><li>It should encapsulate specific business logic.</li><li>The view model should generally not contain state, even though Stateful ViewModels are acceptable in case the models/collection should be locally manipulated Example: sorting/filtering/adding/removing items from a collection etc.</li><li>It should be unit testable.</li><li>For better readability, <a href="http://rx-marin.com/post/rxswift-rxcocoa-custom-convenience-operators-part1/">custom operators</a> have to be implemented to serve specific Observable needs.</li></ul><p><a href="https://github.com/StanevPrime/PrimeHoldingiOSTemplatesSample/blob/master/Test1/ViewModels/DetailsViewModel.swift">ViewModel example</a></p><h3>Inputs</h3><ul><li>ViewModelInput is an interface that combines all inputs (methods) that the ViewModel should implement</li><li>For each input (method) a Publish/Behaviour Subject is declared so that all actions are transformed to Observables.</li></ul><h3>Outputs</h3><ul><li>ViewModelOutput is an interface that combines all outputs (<a href="https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#driver">Drivers</a>) that the ViewModel should implement</li><li>Each output is represented as a <a href="https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#driver">Driver</a> of presentable data (ViewState) that the consumer will use in order to update UI elements accordingly</li></ul><h3>ViewModelType</h3><p>ViewModelType composes Input and Output. The ViewController is only aware of the ViewModelType as the ViewModel itself is hidden from it, so the only way to access the Inputs/Outputs is the following:</p><ul><li>viewModel.input.*</li><li>viewModel.output.*</li></ul><p>The above setup improves readability and allows implementing bindings for output streams.</p><h3>Bindings</h3><p>In order to glue View Layer (ViewController/View) with a ViewModel a ViewModelOutput/ViewModelInput extensions function should be implemented.</p><h3>View Data Bindings</h3><p>Where possible, the View Model’s Input/Output should be directly connected to the View Binding via extensions. <a href="https://github.com/ReactiveX/RxSwift/tree/master/RxCocoa/iOS">RxCocoa</a> is an extremely helpful tool for this purpose.</p><p><a href="https://github.com/StanevPrime/PrimeHoldingiOSArchitecture/blob/master/Documentation/Bindings.md">Read More</a></p><h3>ViewModel Composition</h3><p>In case of a complex screen with a variety of components, it should be split up into separate ViewModels wrapped in a single ViewModel via composition/DI (see below). Then that single view model should be instantiated in the ViewController with Dependency Injection (for example<a href="https://github.com/Swinject/Swinject"> <em>Swinject</em></a>)</p><h3>Service</h3><p>The service layer is responsible for handling domain-specific business logic as it’s shared within multiple screens or even for the entire application. The goal is to offload the ViewModel of a shared business logic so that we keep ViewModel light and at the same time we maintain a good separation of concerns.</p><h3>Repository</h3><p>The repository pattern is a design pattern that isolates data access behind interface abstractions. Connecting to the database, Cache, or Web Service and manipulating data storage objects is performed through methods provided by the interface’s implementation. Each Repository contains methods that return Observables. The idea behind this is that when the ViewModel requests data, the Repository will retrieve it from any data source and will provide it via Observables since the data is expected to be fetched asynchronously and the response will not be delivered immediately.</p><p>Using those techniques, helped us significantly improve the code quality for our Android and iOS projects within the company, as the side effects are:</p><ol><li>It’s easier for developers to switch projects because of the common set of standards/patterns</li><li>Having an Android developer transition to working on an iOS project is smooth and effortless since the learning curve is not steep at all</li><li>Developers become more confident when facing different challenges since synchronization of events is easily done.</li><li>Considering the impact of it on the company, I think that development times are reduced and the methodology carries very little technical debt.</li></ol><p>Finally, you can check how a real case scenario would look in action by checking the samples below:</p><p><a href="https://github.com/StanevPrime/PrimeHoldingAndroidTemplatesSample">https://github.com/StanevPrime/PrimeHoldingAndroidTemplatesSample</a></p><p><a href="https://github.com/StanevPrime/PrimeHoldingiOSTemplatesSample">https://github.com/StanevPrime/PrimeHoldingiOSTemplatesSample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02794cce4d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prime-holding-jsc/common-architectural-design-pattern-for-ios-and-android-applications-f02794cce4d4">Common architectural design pattern for iOS and Android applications</a> was originally published in <a href="https://medium.com/prime-holding-jsc">Prime Holding JSC</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>