<?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 Erkan Sahin on Medium]]></title>
        <description><![CDATA[Stories by Erkan Sahin on Medium]]></description>
        <link>https://medium.com/@erkansahin?source=rss-c03ed186b7af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4jQ5wEl2z6u6ePpYzPe7gg@2x.jpeg</url>
            <title>Stories by Erkan Sahin on Medium</title>
            <link>https://medium.com/@erkansahin?source=rss-c03ed186b7af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:38:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erkansahin/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[Building A Video-driven Social App With Flutter: Challenges And How To Overcome Them]]></title>
            <link>https://blog.startupstash.com/building-a-video-driven-social-app-with-flutter-challenges-and-how-to-overcome-them-43a231de9f84?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a231de9f84</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[founders]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 19:25:50 GMT</pubDate>
            <atom:updated>2022-10-04T12:43:52.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gx7mlGM8_ur9Tz5O0Md6Iw.png" /></figure><p>Having a stable feed experience is essential for a social startup. If your users are disappointed with bugs and sluggishness, they stop using your product no matter what fancy features you build. The users of the app must be satisfied to sustain growth. If the users get disappointed, the dream of becoming the next big thing may remain a dream forever.</p><h3>The Challenge</h3><p>Last year, I started building a social app called <a href="https://sponty.app/">Sponty</a>. It enables people with similar interests to organize and join spontaneous events. The app is video-driven. If users want to create or join an event, they must shoot a video. The app has a vertical video feed similar to Tiktok, where the users can see activities nearby. We needed to be sure that the app was solid with the feed feature since it was the first thing users saw.</p><p>The plan was to release the app for both Android and IOS devices. We had a developer team of three, one of which works on the backend. Not having an army of developers, we had to make wise decisions in the tech stack. Therefore, we chose Flutter for the development framework. Our team was competent but had no prior experience building a video-driven app with Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*0FFQkhcyEXds7tGbOcKgQQ.png" /></figure><h3>Why Flutter?</h3><p>Building and maintaining two separate apps for Android and IOS platforms is a big challenge with a small team. Another hurdle is keeping the stability and performance of the apps in sync. After a deep investigation, we decided Flutter was the best choice for building great cross-platform applications. Flutter unifies developers into a single codebase. It increases the development pace significantly while offering a smooth, native experience.</p><h3>Technical Feasibility</h3><p>We researched on the internet to find out the feasibility of our project. An optimal video feed requires orchestrating multiple video players without jank, memory issues, latencies, and crashes. We realized that there is not enough resource in the community that explains how to build a production-level video feed. Here is an issue that has not been resolved for more than two years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rFDS7aVMcdQJOBwn1hB1A.png" /><figcaption><a href="https://github.com/flutter/flutter/issues/62265">https://github.com/flutter/flutter/issues/62265</a></figcaption></figure><p>The official plugin gives low-level control over video playback. Wrappers around the official plugin are available like <a href="https://pub.dev/packages/chewie">Chewie</a> and <a href="https://pub.dev/packages/better_player">Better Player </a>offering additional features. Also, there are plugins like <a href="https://pub.dev/packages/flutter_vlc_player">VLC Player</a>, <a href="https://pub.dev/packages/fijkplayer">Fijk Player</a>. We dug into many Github issues and checked the pros and cons of each alternative. Finally, we made our choice in favor of the official <a href="https://pub.dev/packages/video_player">Video Player</a> plugin.</p><p>Our main concerns when choosing the plugin were performance and maintainance frequency. The video_player plugin is officially maintained and updated frequently. We did not want to give the destiny of our main feature to a third-party library that may be abandoned in the future. On the other hand, we took the burden of developing the missing aspects of the official video-player plugin.</p><h3>Building The Initial Version</h3><p>Our design required us to have a two-dimensional feed. The user scrolls between activity videos vertically. If the user scrolls horizontally, the camera opens, and the user captures a response video.</p><p>Resource management was crucial for the Feed. We wanted to ensure that low-end devices will not suffer memory issues since video players and camera controllers are resource-demanding. We constructed a complex state machine design in which multiple video players and camera controllers are managed. We were proud to build such a complex architecture and fool enough to think this was a clever solution. In reality, we were only overengineering.</p><h3>Falling into the overengineering trap</h3><p>As we tested our initial version, we encountered many errors with lots of red screens. What is worse, the app suffered in performance on low-end devices. Some users reported that the video feed does not work on their devices at all. Later, we realized that some devices limit the number of video players that can be alive in the app.</p><p>Soon enough, we found out the origin of the problem. We were fighting with the framework. In the beginning, we were aware of how memory-consuming managing multiple cameras and video player controllers could be. Therefore, we took absurdly complicated measures to be ‘safe’ and ‘flexible’ Our mistake was trying to solve the problems we had not suffered yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*m7gn0sHF8KHFWOnJLjJnQg.png" /></figure><p>Lesson learned: Do not overdesign. Writing overengineered code kills productivity and is as harmful as writing spaghetti code.</p><h3>Reboot</h3><p>After some point, we realized that implementing the video feed from scratch is less costly than trying to solve the existing problems. So, we came up with a much simpler and more stable architecture.</p><p>The initial result was astonishing. Many bugs disappeared, and the performance of the feed improved significantly. We reached a milestone where we solved many chronic problems, and the fundamental features of the feed became stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zIIbzGtzssczpRvvZ5b3sg.jpeg" /></figure><h3>Getting production level</h3><p>Our beta users reported that the load time of a feed item is too much. Users do not wait for the videos to load on apps like Instagram and Tiktok. Another problem was that PageView acted weird when inserting a new item into the feed.</p><p>After brainstorming on room for improvements, we came up with several diagnoses:</p><ul><li>The video sizes are too big. It increases both storage costs and video load times.</li><li>It is inefficient to re-buffer a video every time the user views an activity.</li><li>There is no preloading mechanism in the PageView implementation. A video starts buffering if the feed item is on display.</li><li>When a user scrolls towards the end of the feed, more activities should be fetched.</li><li>The PageView should reorder activities concerning parameters like user interests and location when new activities are fetched. The reorder breaks the stability of the feed with the default PageView implementation.</li></ul><h3>The solutions</h3><p>After making the diagnosis, we applied the following solutions to boost the performance of the feed and solve the current bugs:</p><ul><li>Video encoding is a process for making video files smaller through compression. We implemented a mechanism to encode a video before uploading it to the server. Previously, a video of size 41.03 megabytes is reduced to 5.06 megabytes with a slight compromise in video quality. Not only did it improve the video load time, but also reduced the storage costs significantly.</li><li>We implemented caching using <a href="https://pub.dev/packages/flutter_cache_manager">flutter_cache_manager</a>. When the user watches the same video, the app plays the cached video immediately instead of buffering it from the network. The storage costs decreased dramatically.</li><li>For a better user experience, we need to pre-load the videos before the user scrolled to the next activity, but the official PageView doesn’t support that. Therefore, we use a community-supported package called <a href="https://pub.dev/packages/preload_page_view">preload_page_view</a>, which brings this functionality. After implementing this feature, user satisfaction skyrocketed.</li><li>We implemented pagination to fetch activities as the users approach the end of the feed.</li><li>Using PageView.custom constructor solved the problem of item insertion and feed reordering.</li></ul><h3>Conclusion</h3><p>After all these improvements, most bugs disappeared, and the app performance was boosted. Now that Sponty gives its users a native-like experience thanks to Flutter.</p><p>I originally wrote this article two months ago. After architecting and implementing the same feature multiple times, I still find refinements that improve performance.</p><p>This article breaks down the problems we had in Sponty and how we handled the issues. Note that every application has unique needs, and some of the solutions in this article may not apply to your product. The recipe changes if you target Android, IOS, Desktop, and Web users.</p><p>Feel free to share your thoughts, and mention the problems you faced in your app in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a231de9f84" width="1" height="1" alt=""><hr><p><a href="https://blog.startupstash.com/building-a-video-driven-social-app-with-flutter-challenges-and-how-to-overcome-them-43a231de9f84">Building A Video-driven Social App With Flutter: Challenges And How To Overcome Them</a> was originally published in <a href="https://blog.startupstash.com/">Startup Stash</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Architect A Production-Level App In Flutter: Phone Number Authentication - Part 2]]></title>
            <link>https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-part-2-63fff0bb79b1?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fff0bb79b1</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 01:28:07 GMT</pubDate>
            <atom:updated>2021-09-06T05:56:12.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*KZtfhgVtSSeeecX8FiVmNg.png" /></figure><p>In the <a href="https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-263628e1872c">previous part</a>, we implemented the domain and infrastructure layers. Next, we are going to implement the Application and Presentation layers. The application layer is where state management and business logic are handled. My choice of state management package is <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>.</p><p>Although I love Bloc, it requires a lot of boilerplate code to implement. Fortunately, there is a light version of Bloc called <a href="https://bloclibrary.dev/#/coreconcepts?id=cubit">Cubit</a>. It is a subset of Bloc which does not rely on events and instead uses methods to emit new states. If you do not need advanced features like <a href="https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function">debounce</a>, <a href="https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function">throttle</a>, <a href="https://www.woolha.com/tutorials/rxdart-using-map-operators-examples">switchMap</a>, using a cubit will be more than enough for state management.</p><p>Now, we are going to implement a cubit for handling phone number sign-in logic. It uses the authentication service interface in the domain layer to communicate with the Firebase authentication service. It will not explicitly use Firebase in the application layer, which means our cubits will be Firebase independent. We can switch the service provider from Firebase to any other service seamlessly. The reason is that we depend on the abstract IAuthService class rather than a specific service provider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e4504909509ae6afe2c4a7bb2c65311/href">https://medium.com/media/4e4504909509ae6afe2c4a7bb2c65311/href</a></iframe><p>When the user logs in with a phone number, the interaction is as follows:</p><p>The user:</p><ul><li>enters the phone number</li><li>presses the next button</li><li>sees the next button disappear</li><li>sees a loading screen</li><li>receives an SMS code</li><li>enters the SMS code</li><li>is navigated to the home page</li><li>receives an error message if anything goes wrong in the flow</li></ul><p>The scenario above may help us determine the methods and states of the PhoneNumberSignInCubit. We can deduce that the following four methods are needed:</p><ul><li>phoneNumberChanged: To keep the most up to date phone number in the state</li><li>signInWithPhoneNumber : Starts the phone number sign-in process when the user presses the next button</li><li>smsCodeChanged : To keep the most up to date SMS code in the state</li><li>verifySmsCode : To verify the SMS code the user entered</li></ul><p>When the user interacts with the UI through the methods mentioned above, the state of the cubit will change. The UI reflects the state of the cubit. Considering the user interactions and the methods, the state class should keep the following:</p><ul><li>phoneNumber: The phone number the user types</li><li>verificationIdOption: A verification id which will be used to verify the SMS code</li><li>smsCode: The SMS code the user types</li><li>isInProgress : A loading state to understand whether there is an ongoing process</li><li>failureOption :The failure the user encounters if anything goes wrong during the sign-in process</li></ul><p>We are done with the most challenging part of state management which is to construct the state machine. Freezed classes are a perfect candidate for implementing state classes as they are immutable, and support value equality. The PhoneNumberSignInState class will look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c75b6718c4c82ee3da742b3044b7f397/href">https://medium.com/media/c75b6718c4c82ee3da742b3044b7f397/href</a></iframe><p>Observe that there are three additional getters in the state class. These getters are derived from the existing states and their purpose is to simplify the usage of states in the UI. For instance, the UI does not need to know the existence of the verification id. It is just an implementation detail. The only thing the UI cares about is to know when to show the next button, or when to display the SMS code entry form. So, the getters we defined facilitate the logic in the UI quite a lot.</p><p>The state class is ready. We can now jump to the fun part and implement the business logic. Whenever the user types, we need to update the phoneNumber or smsCode in the state accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87613a673947fa62399039720fb66b28/href">https://medium.com/media/87613a673947fa62399039720fb66b28/href</a></iframe><p>When the user presses the <strong>Next </strong>button, signInWithPhoneNumber method is called. Then, existing errors in the state are cleared and in-progress state is emited. The _phoneNumberSignInSubscription will listen to the signInWithPhoneNumber stream defined in the authentication service interface. If a failure is received during the sign-in process, we emit the state accordingly. If the user receives an SMS code successfully, the verification id is emited to the state to be used in the verifySmsCode method later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e14ec90f0e748aa16b71704eeca11623/href">https://medium.com/media/e14ec90f0e748aa16b71704eeca11623/href</a></iframe><p>Do not forget to cancel the stream subscription:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0586faa6fb1f315631a97399878adb8b/href">https://medium.com/media/0586faa6fb1f315631a97399878adb8b/href</a></iframe><p>Once the user enters the SMS code, verifySmsCode of the cubit is called. This method passes the verificationId and smsCode in the state to the authentication service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e6e35b8d9d54e98abb665198d1f258f/href">https://medium.com/media/3e6e35b8d9d54e98abb665198d1f258f/href</a></iframe><h3>Auth Cubit</h3><p>The need for AuthCubit springs from the following requirements:</p><ul><li>When the user opens the app, we need to understand whether the user is already signed in</li><li>If the user is signed in, the phone number of the user is displayed on the home page</li><li>If the user is not signed in, the phone number sign-in page is displayed</li><li>When the user completes sign-in successfully, we redirect the user to the home page</li><li>Also, there will be a logout button on the home page. If the user signs out, we navigate the user to the phone number sign-in page</li></ul><p>The AuthStateclass will be quite straightforward. It will keep two fields:</p><ul><li>userModel: The user that is currently signed in. An empty user model will be kept if the user is not signed in</li><li>isUserCheckedFromAuthService: A boolean flag to understand whether we checked the sign-in status of the user at least once throughout the lifetime of the app. When the app is first opened, our default state assumes that the user is not signed in.isUserCheckedFromAuthService is set to trueafter receiving the actual user information from the userChanges stream.</li></ul><p>The AuthState class looks like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59a921682c26da2fbfea0a558beb815b/href">https://medium.com/media/59a921682c26da2fbfea0a558beb815b/href</a></iframe><p>The AuthCubit methods are also straightforward. _authUserSubscription listens to the authStateChanges stream.</p><p>AuthCubit is a singleton which means that it is created once and lives throughout the app lifetime unless it is disposed manually:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea9371574abe34813684ca11bbeeae9/href">https://medium.com/media/4ea9371574abe34813684ca11bbeeae9/href</a></iframe><h3>Presentation Layer</h3><p>The presentation layer is where our Widgets reside. It should not contain business logic or any infrastructure code. The presentation layer interacts with the Application layer using the methods in cubits and updates itself depending on state changes.</p><p>Also, routing is handled inside the presentation layer. For routing, I use the <a href="https://pub.dev/packages/auto_route">auto_route</a> package, which reduces the boilerplate. The package setup is already done in the <a href="https://github.com/erkansahin/bare-bones">bare-bones</a> template. I advise you to read the official documentation to see the full capabilities of the package.</p><h3>Providing Auth Cubit</h3><p>We need to know the authentication state of the user irrespective of the current route. So, the auth cubit will be provided on top of the MaterialApp and live throughout the app lifetime. It allows us to access the authentication state on any screen of the app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/535101dffffc5babd5410df7610f4188/href">https://medium.com/media/535101dffffc5babd5410df7610f4188/href</a></iframe><p>The initial route of the app is LandingPage . Its only responsibility is to determine where to navigate the user. If the user is signed in, the user is navigated to the HomePage . Otherwise, the user is redirected to the PhoneNumberSignInPage .</p><p>When the landing page is created, there are two possible cases:</p><ul><li>Authentication state is ready before the LandingPage is created</li><li>Authentication state is received after the LandingPage page is built</li></ul><p>The first case is handled in the initState of the LandingPage. According to the state of the AuthCubit, the user is redirected to the right route. If the isUserLoggedInis true, we can safely navigate the user to the HomePage. Else, we need to check an additional flag before navigating the user to the SignInPage. isUserCheckedFromAuthServicetells whether the authenticated user information is available in AuthState. If the query has not resulted when initState is called, we should not take action to navigate the user to any route at this point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8697904a13b02c89b3dbb9af80bae239/href">https://medium.com/media/8697904a13b02c89b3dbb9af80bae239/href</a></iframe><p>In the second case, we navigate the user to the right route when the AuthState is updated. We will add a BlocListener, which will be triggered when the authenticated user information is available. A circular progress indicator is displayed on the screen until the isUserCheckedFromAuthService is updated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4825298fd0e23b12e19b721106d6849/href">https://medium.com/media/b4825298fd0e23b12e19b721106d6849/href</a></iframe><p>If the user is not signed in, PhoneNumberSignInPage is displayed. It will utilize the PhoneNumberSignInCubit to communicate with the outside world. We should provide the PhoneNumberSignInCubit using BlocProvider to be able to call its methods and access its state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98e495f348656f131a9a33893be8558e/href">https://medium.com/media/98e495f348656f131a9a33893be8558e/href</a></iframe><p>We need to place a BlocBuilder to update the UI whenever the PhoneNumberSignInState is updated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/491b072dc1a716d7c240c14c6661855f/href">https://medium.com/media/491b072dc1a716d7c240c14c6661855f/href</a></iframe><p>Whenever the user modifies the phone number input, phoneNumberChanged method is called so that we keep the most up-to-date input in the state.</p><p>If the user presses the <strong>Next </strong>button, signInWithPhoneNumber method is called, which will start the sign-in process. After the process begins, we will hide the next button and display a loading indicator at the center of the screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e17a529a8e00ec83caa5dd01ffe86d21/href">https://medium.com/media/e17a529a8e00ec83caa5dd01ffe86d21/href</a></iframe><p>If the user receives an error during the sign-in process, we should display a toast on the screen which explains the failure. We can use a BlocListener to catch errors. The cubit state is resetted so that the user can try again if something went wrong:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f158e5fde938c83d21893c4b3edd82f8/href">https://medium.com/media/f158e5fde938c83d21893c4b3edd82f8/href</a></iframe><p>If everything goes right, the user will receive an SMS code and a verification id from Firebase. Receiving verification id will trigger our BlocBuilder; so, SMS code entry form will be displayed in the UI.</p><p>When the user modifies the smsCode input, smsCodeChanged method is called so that we keep the most up-to-date input in the state. When the last code digit is typed, verifySmsCode will be triggered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea70b988ce22efa552c32bbf10caf40/href">https://medium.com/media/0ea70b988ce22efa552c32bbf10caf40/href</a></iframe><p>If the user is successfully verified, we should redirect the user to the HomePage. The behavior can be accomplished by a BlocListener that is triggered when the login state of the user is changed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7b5eaec73553da35532926e03901fea/href">https://medium.com/media/d7b5eaec73553da35532926e03901fea/href</a></iframe><p>On the HomePage, the phone number of the signed-in user and a <strong>Logout </strong>button are displayed. For displaying the phone number of the user, we can use a BlocBuilder inside the build function of the home page.</p><p>As a rule of thumb, it is important to place your bloc builders as deep as possible in the widget tree. Also, they should not be triggered in every state change of your bloc/cubit. It is better to use buildWhen conditions in your BlocBuilder or use BlocSelector to watch the value changes for improving performance of your app. In the scope of this tutorial, using buildWhen conditions may not affect the performance significantly. However, you should be using them in a production-level app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5c74d89daaf3179de0f9b8193a2887e/href">https://medium.com/media/c5c74d89daaf3179de0f9b8193a2887e/href</a></iframe><p>Pressing the <strong>Logout </strong>button triggers the signOut method of the AuthCubit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bdc37809eee5f3918dd371b7864f317/href">https://medium.com/media/0bdc37809eee5f3918dd371b7864f317/href</a></iframe><p>When the user signs out successfully, we should redirect the user to the phone number sign-in page. To accomplish this behavior, we can place a BlocListener which triggers when the user is not signed in anymore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b0ed2a55a92d734eff269cd866ca0a/href">https://medium.com/media/43b0ed2a55a92d734eff269cd866ca0a/href</a></iframe><p>That’s it! You have seen the implementation of the phone number sign-in feature in a production-level app. I am aware that it might be difficult to grasp everything at once since there are many packages and concepts involved. I encourage you to analyze what is done in each layer and add a feature to the existing app. I believe adding Google Sign In feature could be a good challenge for you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fi79P9wUfnmPyo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fi79P9wUfnmPyo&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExM3lzejlwdzB5d2dsaWluMW1pbDJ1dXllbWt4ZGM5enVnNGxvZmVndyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fi79P9wUfnmPyo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0a9259b5cb10a38a72cfdde1015400/href">https://medium.com/media/5b0a9259b5cb10a38a72cfdde1015400/href</a></iframe><p>This is the same implementation we used in <a href="https://sponty.app/#/">Sponty</a>. It is a video-driven social media app which is used for spontaneous group gatherings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0sbT4FjJPzuQUUfBctR3Dw.png" /></figure><p>I hope that this tutorial helps you understand how you should organize your code in a production-level application. Feel free to ask any questions in the comments section.</p><p>Thank you for reading, stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fff0bb79b1" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-part-2-63fff0bb79b1">How To Architect A Production-Level App In Flutter: Phone Number Authentication - Part 2</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Architect a Production-Level App in Flutter: Phone Number Authentication]]></title>
            <link>https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-263628e1872c?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/263628e1872c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 00:34:42 GMT</pubDate>
            <atom:updated>2021-09-06T01:36:39.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*56dabNrDBnpH7l5k4vxKFQ.png" /></figure><p>When developers jump into Flutter, they can find various resources which help them get started. Resources such as tutorials, repositories, and UI challenges can turn a beginner into an intermediate Flutter developer. Soon enough, the developers fall in love with the framework.</p><p>Building amazing-looking UI’s is the most fun aspect of Flutter. However, a beautiful UI/UX backed by no maintainable business logic can’t get you too far. If you aim to become an advanced Flutter developer, unfortunately, there are not many resources out there to help.</p><p>Believing that no Flutter developer should feel alone throughout this journey, I decided to share my experiences on building a production-level app. So, I open-sourced the Phone Number Sign In feature of<a href="https://sponty.app/#/"> Sponty</a> along with its production-level clean architecture.</p><p>I will show how to architect a Flutter app with phone number sign-in feature using Firebase. The scope of the article is limited to architecture and how to handle state management. You can find the full source code of the project in <a href="https://github.com/erkansahin/phone_number_sign_in">Github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*T2lEUMEIoaBeNp-Lp6rpXg.gif" /></figure><p>To get started, you can use the <a href="https://github.com/erkansahin/bare-bones">bare-bones</a> project template. It pre-configures the required dependency injection, routing, and linter so that you don’t have to set all those up. The bare-bones folder structure looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*UuqktltVIF87fZnRMAGmXg.png" /></figure><h3>Domain Layer</h3><p>At first, we create a folder under the domain layer for the authentication feature. This layer keeps auth user model class, custom authentication failures, and the interface used to communicate with the authentication service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*AqMcspU8WQ_dxsd3ezszig.png" /></figure><p>The<a href="https://pub.dev/packages/freezed"> freezed</a> package is used for generating model classes. One of the advantages of freezed is value equality support. Without freezed, == returns true if the object references of two instances are identical. Freezed overrides the == operator and hashCode, which saves us from writing boilerplate code. You can read more about equality in the Dart language from the <a href="https://dart.dev/guides/language/effective-dart/design#equality">official documentation</a>.</p><p>Our <a href="https://github.com/spontyapp/phone_number_sign_in/blob/main/lib/domain/auth/auth_user_model.dart">user model class</a> is quite simple. Any signed-in user will have a user id and a phoneNumber. When the user is not signed in, both fields will be empty strings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17fce83c9b33d60b4d0ece5b1fdce2bb/href">https://medium.com/media/17fce83c9b33d60b4d0ece5b1fdce2bb/href</a></iframe><p>There exist some failure scenarios that need to be handled when the user wants to log in with a phone number:</p><ul><li>The user may enter an invalid phone number.</li><li>The timeout to enter the SMS code may be expired.</li><li>The verification code the user entered may be incorrect.</li><li>The user session may expire.</li><li>The server might be down.</li><li>The user abuses the authentication service with too many requests.</li><li>The user device does not support phone number sign-in(emulators).</li></ul><p>We need to handle the above scenarios and inform our users about what is going wrong. <a href="https://github.com/spontyapp/phone_number_sign_in/blob/main/lib/domain/auth/auth_failure.dart">AuthFailure</a> class contains the errors users may receive during phone number sign-in. Again, it is a freezed class, a union type, to be more specific. Dart currently does not support unions; however, freezed offers union classes with a syntax similar to Kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d3bb8e51e7741869397b6ba8552dca/href">https://medium.com/media/f5d3bb8e51e7741869397b6ba8552dca/href</a></iframe><p>The Authentication service is responsible for handling four main functionalities:</p><ul><li>Notify when the authentication status changes.</li><li>Logout from the service.</li><li>Send phone number to the backend, emit error messages, if any.</li><li>Send SMS code to the backend for verification, emit error messages, if any.</li></ul><p>We create an interface to communicate with an authentication service. So, the application layer will only know about the interface, which will make the authentication service independent of Firebase. The methods below are not strictly related to any authentication service. Abstraction of the authentication service allows a change of backend to be seamless(Firebase, AWS, Azure).</p><p>The return types used comes from a functional programming package called <a href="https://pub.dev/packages/dartz">dartz</a>. When the user enters the phone number and presses the send button, it will trigger the signInWithPhoneNumbermethod. It will either emit an AuthenticationFailure or a verificationId. Receiving a verification id means that the user will get an SMS message. When the user enters the smsCode, we will send it to the server along with the verification id to complete sign-in. It returns either an AuthFailure or return success by returning Unit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a1020d354925b2278c7ae2398ead5c3/href">https://medium.com/media/6a1020d354925b2278c7ae2398ead5c3/href</a></iframe><h3>Infrastructure Layer</h3><p>Now that the abstraction for the authentication service is completed, we are ready to implement FirebaseAuthService . Similar to the domain layer, a subfolder for the authentication feature is created. Below this folder, two files exist:</p><ul><li>FirebaseAuthService which implements IAuthService.</li><li>An extension method for mapping a firebase user to our AuthUserModelclass.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*KHmZbvsQbMv--ijupAqUtg.png" /></figure><p>Dependency injection is used to instantiate FirebaseAuthService. If you are not familiar with<a href="https://stackoverflow.com/questions/130794/what-is-dependency-injection"> dependency injection</a> or the <a href="https://pub.dev/packages/injectable">injectable</a> package, you can examine the <a href="https://medium.com/r?url=https%3A%2F%2Fresocoder.com%2F2020%2F02%2F04%2Finjectable-flutter-dart-equivalent-to-dagger-angular-dependency-injection%2F">linked resources</a>. InjectableModule class is needed to register third party dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/401f3d32de894ce6d69f43b107019215/href">https://medium.com/media/401f3d32de894ce6d69f43b107019215/href</a></iframe><p>Next, we create the FirebaseAuthService class which implements the IAuthService. The injectable package will create a singleton instance of FirebaseAuthService for us. If you ever want to switch the authentication service from Firebase to AWS, the only thing you need to do is to implement the IAuthServiceinterface for AmazonAuthService and register it as IAuthService. This gives the flexibility of switching between different service providers without the need of modifying business logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1fac54b0a1e6bc55ffd692ec94ef70e/href">https://medium.com/media/c1fac54b0a1e6bc55ffd692ec94ef70e/href</a></iframe><p>You can find the setup instructions of Firebase Phone Authentication from the <a href="https://firebase.flutter.dev/docs/auth/phone/">official documentation</a>. The scope of this article does not cover the setup of Firebase Auth.</p><p>signInWithPhoneNumber is the trickiest method we will write because of the way verifyPhoneNumberis implemented by Firebase. There are four callbacks Firebase asks us to handle:</p><blockquote><a href="https://firebase.flutter.dev/docs/auth/phone/#verificationCompleted"><strong>verificationCompleted</strong></a>: Automatic handling of the SMS code on Android devices.</blockquote><blockquote><a href="https://firebase.flutter.dev/docs/auth/phone/#verificationFailed"><strong>verificationFailed</strong></a>: Handle failure events such as invalid phone numbers or whether the SMS quota has been exceeded.</blockquote><blockquote><a href="https://firebase.flutter.dev/docs/auth/phone/#codeSent"><strong>codeSent</strong></a>: Handle when a code has been sent to the device from Firebase, used to prompt users to enter the code.</blockquote><blockquote><a href="https://firebase.flutter.dev/docs/auth/phone/#codeAutoRetrievalTimeout"><strong>codeAutoRetrievalTimeout</strong></a>: Handle a timeout of when automatic SMS code handling fails.</blockquote><p>Multiple callbacks can be triggered in the same signInWithPhoneNumber process. For instance, the codeSent callback is triggered when the SMS code is received from Firebase. If the user has an Android device, verificationCompleted callback is triggered as well to make the user automatically signed in without the need of entering an SMS code. Also, the user can receive verification failures during the process. We need to represent these errors in the UI.</p><p>Most tutorials couple the UI with the logic in the callbacks. The UI should not contain anything related to the Firebase Auth implementation. signInWithPhoneNumber returns a stream. If the codeSent callback is triggered, a verification id is yielded. If the verification fails for whatever reason, the method yields an AuthFailure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/520d4f803439c23fbade8a575140c68a/href">https://medium.com/media/520d4f803439c23fbade8a575140c68a/href</a></iframe><p>If the signInWithPhoneNumber method works successfully, it returns a verification id through the codeSent callback. The user’s device should soon receive an SMS code from Firebase. At this point, we will ask the user to fill in the SMS code.</p><p>verifySmsCode sends the entered SMS code to the Firebase Auth to complete the verification. If something goes wrong, the method returns the corresponding failure. For instance, the user may enter the SMS code incorrectly. In this case, an invalid verification code failure is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6547545cacdfd9c31a85ab2025510a87/href">https://medium.com/media/6547545cacdfd9c31a85ab2025510a87/href</a></iframe><p>We also need a method to make the user sign out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538e35929afac741ffd8a3bf0d4ca40a/href">https://medium.com/media/538e35929afac741ffd8a3bf0d4ca40a/href</a></iframe><p>Neither the signOut nor the verifySmsCodegives us a clue about whether the authentication state of the user changed. Fortunately, Firebase provides us a stream to watch authentication state changes. The authStateChanges stream is used to understand whether the user is signed in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1dceffe75a4e072699294b3ff44c10b/href">https://medium.com/media/b1dceffe75a4e072699294b3ff44c10b/href</a></iframe><p>With the implementation of FirebaseAuthService, Domain and Infrastructure layers are done. Congratulations! In the next part, we will handle the state management in the Application layer. Finally, we will integrate the business logic component into the UI in the presentation layer. See you in the next part:</p><p><a href="https://medium.com/@erkansahin/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-part-2-63fff0bb79b1">Part 2: How To Architect A Production-Level App In Flutter: Phone Number Authentication</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FsSnN2QaBF222cP25j9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ftheoffice-sSnN2QaBF222cP25j9&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2FsSnN2QaBF222cP25j9%2Fgiphy.gif%3Fcid%3D790b761101635ea82a1f729fc134d7d1b9f42447f88794ac%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/50f469e3374b6d161c383c1d22b51311/href">https://medium.com/media/50f469e3374b6d161c383c1d22b51311/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263628e1872c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-263628e1872c">How to Architect a Production-Level App in Flutter: Phone Number Authentication</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to architect a production-level app in Flutter]]></title>
            <link>https://itnext.io/how-to-architect-a-production-level-app-in-flutter-251335cae1bb?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/251335cae1bb</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[bloc-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 00:01:03 GMT</pubDate>
            <atom:updated>2021-09-06T05:55:46.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Architect a Production-Level App in Flutter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*QtL_yVAEio9iJm1jSQlgNw.png" /></figure><h3>Technical Debts</h3><p>Flutter helps developers build great UIs quickly. When a team of developers starts a new project, they implement one feature after another. In the early stages of the development, the production pace will most probably satisfy the clients. The excitement goes on until the developers realize that they are at a point where they cannot scale up the project anymore. Spaghetti code causes the pace of development to reach a plateau quickly. Making even a slight change becomes way too expensive since various bugs pop up. The project ends up becoming a failure eventually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*IZy7ExUNf1sBN2TN_mZqqg.png" /></figure><h3>Overpaying Debts</h3><p>Flutter Developers need to follow a clean architecture in which they can maintain their projects with ease. However, the Flutter Community does not have a widely accepted solution for writing clean code. Developers confuse overusing complex patterns, with clean coding. When you write code that solves problems you do not have, you are overengineering. Writing overengineered code is as harmful as spaghetti code since it halts productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*j6E1uFyjZHBV0Ni_VWfFBg.png" /></figure><h3>Seeking the clean way</h3><p>When I first started developing with Dart and Flutter, I knew that I should write clean code, but I had no clue where to start. I saw many developers on the internet who claimed to write with clean architecture. However, most of these tutorials were overengineered and were not maintainable in the long run.</p><p>During my research of finding the ‘best’ architecture, I encountered the <a href="https://www.youtube.com/watch?v=RMiN59x3uH0&amp;list=PLB6lc7nQ1n4iS5p-IezFFgqP6YvAJy84U">Domain-Driven Design(DDD) tutorials</a> published by <a href="https://www.youtube.com/channel/UCSIvrn68cUk8CS8MbtBmBkA">Reso Coder</a>. This architecture made a lot of sense, and it was love at first sight. Reso Coder separates the app into four main layers.</p><ul><li>Domain: The layer where your model classes, custom failure classes, and interfaces exist (e.g. user_model.dart).</li><li>Infrastructure: The layer that implements the interfaces you defined in the Domain layer (e.g. firebase_auth_service.dart).</li><li>Application: The business logic and state management are handled in this layer (e.g. auth_cubit.dart).</li><li>Presentation: The UI of your app. The presentation layer is where your Widgets reside (e.g. sign_in_page.dart).</li></ul><p>‘Everything has a place and everything in its place, I thought. So I began practicing with the DDD architecture on some mini-projects.</p><h3>How did the Sponty app begin?</h3><p>Last August, I met a great guy on Reddit. He saw one of the mini-projects I implemented using DDD and asked whether I wanted to work with him on his upcoming project. To cut a long story short, we formed a remote team of 3 Flutter Developers. We agreed on building a game-changer social media platform that enables people with similar interests to organize and join spontaneous events. We named it <a href="https://sponty.app/#/">Sponty</a>. At first, we discussed the nontechnical details of the project. We eventually started talking about what architecture we will use. The challenge of the project has been to orchestrate the video player, camera, and map at the same time. This requires us to be careful about memory leaks since the memory consumption of each component is high. If we had poor architecture, the performance of Sponty would have suffered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*moyIf_2g5ADIlQiy519jsQ.png" /><figcaption><a href="https://sponty.app/#/">Sponty</a></figcaption></figure><h3>Challenges of vanilla DDD</h3><p>I proposed using the DDD architecture. It was clean and maintainable in the long run. On top of that, I had a good amount of experience using DDD, and I was confident with this choice. All of us agreed and started development with the DDD architecture. The rest of the team loved DDD as much as I did. However, there was a problem with the domain layer of the vanilla DDD. Value objects comprise entities rather than using primitive types. Soon enough, I realized that writing value objects for each of the entities were exhausting. It was going to slow us down a lot with little gained value. We modified the domain layer in the original architecture and implemented it in our style. This improved our productivity significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*bc73WQBIbsZc3XIpRHXx6A.png" /><figcaption><a href="https://resocoder.com/2020/03/09/flutter-firebase-ddd-course-1-domain-driven-design-principles/">The original domain layer architecture by Resocoder</a></figcaption></figure><h3>State Management</h3><p>For the state management, we needed a solution that cherishes separation of concerns; one solution that will not hand us out to dry in the long run. We agreed on using <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> as it was the most recommended state management solution for large-scale apps. None of us were experts in the BLoC pattern; we had only the basics. It was going to be a challenge for all of us until we got used to the BLoC pattern as it had a higher learning curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*43IQzB5u6v4eSOSCMsUnCg.png" /><figcaption><a href="https://pub.dev/packages/flutter_bloc">Flutter Bloc library by Felix Angelov</a></figcaption></figure><h3>Challenges of BLoC</h3><p>flutter_bloc library met our initial expectations. One of the most important benefits of using flutter_bloc is the support of <a href="https://medium.com/u/bd78eebef416">Felix Angelov</a> and the community. The developers in the <a href="https://discord.com/invite/Hc5KD3g">official Discord channel</a> of flutter_bloc answer all questions we have in our minds. However, there were still some minor obstacles while using BLoC:</p><ul><li>It requires excessive boilerplate even for simple state management.</li><li>It is difficult to understand/follow when the state is going to be updated as the yieldcommand works asynchronously.</li><li>Bloc-to-bloc communication is difficult. yield command does not work as expected when you call it from an inner scope.</li></ul><p>These reasons caused an increase in both our development and debugging time. At a long debugging night, I encountered Cubit which ended up solving most of the problems we faced thanks to <a href="https://medium.com/u/bd78eebef416">Felix Angelov</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*c8zJe80bITwcEHP64YVLaw.png" /></figure><h3>Advantages of Cubit</h3><p>There are many advantages of choosing Cubit over Bloc. The two main benefits are:</p><ul><li>Cubit is a subset of Bloc; so, it reduces complexity. Cubit eliminates the event classes.</li><li>Cubit uses emitrather than yield to emit state. Since emit works synchronously, you can ensure that the state is updated in the next line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*lUEYe3TFZehHWF2m9yvvMQ.png" /></figure><p>Switching to Cubit increased our pace of development significantly. At first, we used it only for managing the state of brand new features. Later, we converted our previous Blocs to Cubits. You do not need Bloc unless you need advanced features like <a href="https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function">debounce</a>, <a href="https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function">throttle</a>, <a href="https://www.woolha.com/tutorials/rxdart-using-map-operators-examples">switchMap</a>, etc. Would you like to know how many times we need Bloc in our entire project? Not even once.</p><p>Lesson learned: always start with Cubit for your state management problem. Switch to Bloc only after you realize that Cubit does not solve your problem. I guarantee that it will save a lot of development and debugging time. Also, your business logic code will become more understandable and easy to follow. Most newcomers are afraid of Bloc since it is difficult to understand. I recommend you try Cubit before giving a shot to other state management solutions. You will not regret it.</p><h3>Expect more content soon</h3><p>The Flutter community is filled with content that is helpful for beginners but lacks content that shows how things work on production-level projects.</p><p>The first article is aimed to reflect an overview of the architectural choices we made in our project. In the upcoming articles, I will get deeper into the architecture and will present lots of code.</p><ul><li><a href="https://itnext.io/how-to-architect-a-production-level-app-in-flutter-phone-number-sign-in-263628e1872c">How to Architect a Production-Level App in Flutter: Phone Number Authentication</a></li></ul><p>We have gained great experiences while developing <a href="https://sponty.app/#/">Sponty</a> and are willing to share it with the community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251335cae1bb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-architect-a-production-level-app-in-flutter-251335cae1bb">How to architect a production-level app in Flutter</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGBoost Algorithm on the Otto Dataset]]></title>
            <link>https://medium.com/@erkansahin/xgboost-algorithm-on-the-otto-dataset-253e424e693?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/253e424e693</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Thu, 02 May 2019 20:02:23 GMT</pubDate>
            <atom:updated>2019-05-02T20:02:23.455Z</atom:updated>
            <content:encoded><![CDATA[<p>XGBoost is an implementation of the famous Gradient Boosting Algorithm. It is described as a black box model. It works well; however, grasping what is going on inside the algorithm is not easy.</p><p>The speed and predictive power of the algorithm is the main reason why it is well known. Today, we will create and have a practical experience with an XGBoost model.</p><p>We start by importing necessary libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ih2DWJVD3C-AqFomE7128A.png" /></figure><p>We load our data from the csv file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KVe5dCNTObu7PUuJNZMIg.png" /></figure><p>Let’s examine our data and see what kind of data we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCjU6KaFGGyJ4XTsxA0j-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qfpnjf9r5WNtImyPEb_DmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmRZfhcP2P-2L-Dw3oB4OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyaVWcruFWcF8sWvyhD39Q.png" /></figure><p>There exists 95 columns in the dataset. One of them keeps only id’s of each data point. Therefore, it does not store any valuable information. Therefore, we will discard it from the dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhOVRLQJkRCRJTuiHrLPzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-KrRpjqhAd0-fFmxG3mEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lq6LDymdMwEHyl19XweoaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzD3iMeYtP22xd6npO09gg.png" /></figure><p>The last column contains labels. The columns in the middle are features. There are 93 of them. Let’s observe the label format of our examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*j7fDhEpmTO2l7DEegOlJ0w.png" /></figure><p>As you see the format of our target is in string. Let’s convert it to integer values and modify our dataset for simplicity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLzeX8XCkJVXdr3rVyu6Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*8IWD9K1BUS1F-XvHOb_-yg.png" /></figure><p>Let&#39;s seperate features from labels by dropping labels from our dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8M2Fc_riMsEPHM77mKRe5A.png" /></figure><p>Before the learning we will use the cross validation to evaluate the our error rate. To do that, we are going to use first 1000 training example to calculate training and validation error. StratifiedKFold in sklearn is used for cross validation.</p><p>Basically, XGBoost will divide the training data in `nfold` parts, then XGBoost will retain the first part and use it as the test data. Then it will reintegrate the first part to the training dataset and retain the second part, do a training and so on...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vACaASa4cJFg8MAkXSLVpw.png" /></figure><p>Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data.</p><p>As the number of trees we use increases, the amount of overfitting increases in XGBoost. Let’s observe the training error and validation error as the number of trees changes. To do that, we will draw a validation curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWdLCq_3rDuWuiswacZ7xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*qgKBcAudmdDmQod6oT6MlQ.png" /></figure><p>The training error decreases as the number of trees increases since our classifier fits the training set better. However, it loses its generalization power. The gap between training error and the cross validation increases as overfitting increases.</p><p>Let’s see the shape of our features and labels. Then, create our classifier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHhNrqErinnbjfucDqecHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwN5TG3ugoT6Ge1vOhKiuw.png" /></figure><p>Create the classifier with 50 trees and fit our data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOAA4ogi7OWeDRQF9PpUBw.png" /></figure><p>Each feautere has a certain amount of contribution for information gain. As the number of features increases, our model becomes more prone to overfitting. We should select top features that gives us most valuable information in order to avoid overfitting. XGBoost has an attribute called feature importances. It gives us contribution of each feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFnwgzVAE5Dl-CGs5WBo5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iER-bSkmq33xWSeI480ljQ.png" /></figure><p>Let’s see top 10 features that gave the most significant contribution for classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJE6lOlsv9SnXbSPl4ZJGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CtTCC--aSBUyUA7fqPZ7w.png" /></figure><p>Let&#39;s see how the accuracy of our classifier changes as we use more features among the top 10 features:</p><p>Do train-test split and train our model with our training data with 50 tree estimators. We use %90 of our data for data for training and %10 for testing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4bVTTXZlGQgIFDnlnuc0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0tO9Kj-hiClPzhmQ_wS6g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253e424e693" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Statistical Approach on the Wine Dataset]]></title>
            <link>https://medium.com/@erkansahin/a-statistical-approach-on-the-wine-dataset-98a2f7b77975?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a2f7b77975</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[modelling]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 20:10:22 GMT</pubDate>
            <atom:updated>2019-03-26T17:53:21.522Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Wine tasting</strong> is the sensory examination and evaluation of <a href="https://en.wikipedia.org/wiki/Wine">wine</a>. While the practice of wine tasting is as ancient as its production, a more formalized methodology has slowly become established from the 14th century onwards. Modern, professional wine tasters (such as <a href="https://en.wikipedia.org/wiki/Sommelier">sommeliers</a> or buyers for <a href="https://en.wikipedia.org/wiki/Retailer">retailers</a>) use a constantly evolving specialized terminology which is used to describe the range of perceived flavors, aromas and general characteristics of a wine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmaMULF8Xyw6TW_Me1lReA.png" /></figure><p>Can we use Machine Learning in order to predict a class of a wine? Why not!</p><p>Today, we are going to explore a dataset of wines. There exist three classes of wines in the dataset. Our task is to explore the dataset and create a classifier that figures out the type of a glass of wine using 2 of the features.</p><p>The data came from a chemical analysis of wines are grown in the same region in Italy but derived from three different cultivars.</p><p>The analysis determined the quantities of 13 constituents found in each of the three types of wines.</p><p>Let’s get the ball rolling and get our hands dirty!</p><p>We start off by importing libraries we are going to use:</p><pre>import numpy as np<br>import pandas as pd<br>import plotly<br>import plotly.graph_objs as go<br>import matplotlib.pyplot as plt<br>from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot<br>from scipy.stats import multivariate_normal<br>from sklearn.feature_selection import SelectKBest<br>from sklearn.feature_selection import chi2<br>from sklearn.metrics import accuracy_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import MinMaxScaler</pre><pre>init_notebook_mode(connected=True)# Here we activate plotly on Jupyter Notebook<br>plotly.offline.init_notebook_mode()</pre><p>Great! We are ready to read our data now. We are going to put our data into a pandas data frame. Let’s read the data and name the columns with feature names.</p><pre>df = pd.read_csv(‘wine.data.txt’, sep=”,”, header=None)<br>df.rename(columns={0: ‘Type’, 1: ‘Alcohol’, 2: ‘Malic acid’, 3: ‘Ash’, 4: ‘Alcalinity of ash’, 5: ‘Magnesium’,<br> 6: ‘Total phenols’, 7: ‘Flavanoids’, 8: ‘Nonflavanoid phenols’, 9: ‘Proanthocyanins’,<br> 10: ‘Color intensity’, 11: ‘Hue’, 12: ‘OD280/OD315 of diluted wines’, 13: ‘Proline’}, inplace=True)<br>labels = df[‘Type’]<br>features = df.drop(labels=[‘Type’], axis=1)</pre><p>We created our pandas data frame. Let’s see how our data looks like:</p><pre>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qN1kIkc5NODS01findjgTQ.png" /></figure><pre>features.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udkWaGfis59OFxkp1pSe2w.png" /></figure><p>Now that we have a better idea of the data we have. As you can see the scales of features vary significantly. Nonflavanoid Phenols takes a maximum value of 0.66 whereas Proline takes minimum value of 278. This may ruin the accuracy of our classifier.</p><p>Machine Learning algorithms don’t perform well when the input numerical attributes have very different scales. There are two common ways to get all attributes to have the same scale: min-max scaling and standardization. Min-max scaling (many people call this normalization) is quite simple: values are shifted and rescaled so that they end up ranging from 0 to 1. We do this by subtract‐ ing the min value and dividing by the max minus the min. Scikit-Learn provides a transformer called MinMaxScaler for this.</p><p>In our case, we will apply normalization to our features in order to range each of them between 0 and 1. We can do it with the following code:</p><pre>scaler = MinMaxScaler()<br>normalized = scaler.fit_transform(features.astype(float))<br>features = pd.DataFrame(normalized)<br>features.rename(<br> columns={0: ‘Alcohol’, 1: ‘Malic acid’, 2: ‘Ash’, 3: ‘Alcalinity of ash’, 4: ‘Magnesium’, 5: ‘Total phenols’,<br> 6: ‘Flavanoids’, 7: ‘Nonflavanoid phenols’, 8: ‘Proanthocyanins’, 9: ‘Color intensity’, 10: ‘Hue’,<br> 11: ‘OD280/OD315 of diluted wines’, 12: ‘Proline’}, inplace=True)</pre><p>First, we created a MinMaxScaler instance. Then, we piped our features into the Scaler. Finally, we named the columns again since they are vanished after applying the normalization operation.</p><p>Let’s see how our data looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfZYjbW3H-qj8PITKN-eeQ.png" /></figure><pre>features.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGzmBOzWYuoSuyKm919Rlw.png" /></figure><p>Our data looks healthier now. Preprocessing process is done. It is time for us to choose 2 features to create our classifier. Our aim is to choose the ones that maximize information gained about the classes.</p><p>As the saying goes: garbage in, garbage out. Your system will only be capable of learning if the training data contains enough relevant features and not too many irrelevant ones. A critical part of the success of a Machine Learning project is coming up with a good set of features to train on.</p><p>If we use too many features, then we will need a lot of data to train the model. You can go out and collect more data for solving the problem of overfitting. But what if we can’t get more data? What are we going to do? Are we going to sit and pray to the god to send us more data?</p><p>Of course, feature selection is not the only alternative in order to make our model simpler. Regularization can be applied and this helps the classifier to generalize better. However, this might not be enough all the time.</p><p>Fortunately, Sklearn has a feature selection algorithm called k-best. It uses chi2 to evaluate each feature and give them scores respectively. It returns k most relevant ones to us so that we could select which features to use.</p><p>Sklearn implementation of k-best feature selection is like the following:</p><pre>best_features = SelectKBest(score_func=chi2, k=13).fit(features, labels)<br>df_scores = pd.DataFrame(best_features.scores_)<br>df_columns = pd.DataFrame(features.columns)</pre><p>Let’s see the scores of each feature visually. We will use Plotly library to visualize our result by means of a bar chart:</p><pre>f = df_columns.values.tolist()<br>s = df_scores.values.tolist()<br>feature_list = []<br>scores_list = []<br>for i in range(len(f)):<br> feature_list.append(f[i][0])<br> scores_list.append(s[i][0])<br> <br>trace = go.Bar(x = feature_list,<br> y= scores_list)<br>data = [trace]<br>layout = {‘title’:’Feature Importance with respect to chi2&#39;,<br> ‘xaxis’: {‘title’:’Features’},<br> ‘yaxis’: {‘title’:’Scores’}}<br>fig = go.Figure(data=data,layout=layout)<br>iplot(fig)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGRDrjgUBodqF3zDGHnVZg.png" /></figure><p>We have a better idea about the relevance of the features now. The given order of the feature importance might not be optimal. You should experiment with the top ones and see which ones do better. It seems that selecting Flavanoids and Proline as features would not be a bad choice.</p><pre>selected = [‘Proline’, ‘Flavanoids’]<br>selected_features = features[selected]</pre><p>Let’s split our data to train and set tests. It is very important that dataset is shuffled well to avoid any element of bias/patterns in the split datasets before training the ML model. Our data came ordered so we should shuffle our<br>dataset during partitioning. Shuffling should not be done in all kinds of data. However, it is better to shuffle the dataset in our case since it is not time-series data. We will use %80 of our data for training and will keep %20 for testing. If we had a lot more data, we would partition our data differently. If you have big data, have millions of examples in your dataset, you should probably put %99 of your data for training and keep %1 for validation. This is because the main problem we have today is overfitting. We have huge neural networks. They are very prone to overfitting. You will want to put as much data as possible to feed your neural network model.</p><p>If we come back to our problem, we can do the partition like the following:</p><pre>X_train, X_test, y_train, y_test = train_test_split(selected_features, labels, test_size=0.2, random_state=42,<br><br>                                                    shuffle=True)</pre><p>Our dataset consists of 3 classes. In order to distinguish each class from one another, we should get more information about the distribution of each class examples. Then, we will use this information to get a prediction.</p><p>Let’s start by separating each class in the training set:</p><pre>def seperate_class_examples(training_features, training_labels, features_selected):<br> type1_indices = training_labels[training_labels == 1].index<br> type2_indices = training_labels[training_labels == 2].index<br> type3_indices = training_labels[training_labels == 3].index<br> type1_samples = training_features.loc[type1_indices, features_selected]<br> type2_samples = training_features.loc[type2_indices, features_selected]<br> type3_samples = training_features.loc[type3_indices, features_selected]<br> return [type1_samples, type2_samples, type3_samples]</pre><pre>def gaussian_mle(data):<br>    mu = data.mean(axis=0)<br>    var = np.dot((data - mu).T, (data - mu)) / data.shape[0]  # this is slightly suboptimal, but instructive</pre><pre>return mu, var</pre><p>We will use these functions above for our operation. Later,</p><pre>type1_samples, type2_samples, type3_samples = seperate_class_examples(X_train, y_train, selected)<br>mu1, cov1 = gaussian_mle(type1_samples)<br>mu2, cov2 = gaussian_mle(type2_samples)<br>mu3, cov3 = gaussian_mle(type3_samples)</pre><p>We got mean and covariance values of each class. We will use this information to do Maximum Likelihood Estimation(MLE). But first, let’s have a look at the distributions of each class visually:</p><pre>def draw_density(gaussian,features):<br> x, y = np.mgrid[0:1:.01, 0:1:.01]<br> pos = np.dstack((x, y))<br> fig2 = plt.figure()<br> ax2 = fig2.add_subplot(111)<br> ax2.contourf(x, y, gaussian.pdf(pos))<br> if gaussian == gaussian1:<br> plt.title(‘Distribution of Class 1’)<br> elif gaussian == gaussian2:<br> plt.title(‘Distribution of Class 2’)<br> elif gaussian3 == gaussian:<br> plt.title(‘Distribution of Class 3’)<br> plt.xlabel(features[0])<br> plt.ylabel(features[1])</pre><pre> plt.show()</pre><pre>draw_density(gaussian1,selected)<br>draw_density(gaussian2,selected)<br>draw_density(gaussian3,selected)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*CretP0gMbtr_wQhNRcsnJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*muBaYdCkYWh0FDatXDiQpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*WOupwRePMfdjKAWs9xiSVQ.png" /></figure><p>As you see the distribution of each class is different from each other. We can use this in order to predict the examples in our test sets. We can do it by using the Probability Density Function of each class. We will pipe our test set features into the PDF of each function. This will return the unnormalized probability value of the given example belong to that class.</p><pre>pdf1 = gaussian1.pdf(X_test)<br>pdf2 = gaussian2.pdf(X_test)<br>pdf3 = gaussian3.pdf(X_test)</pre><p>We will use the returned values to make our prediction. The returned value from one function looks like this:</p><pre>print(pdf1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*fqx2hW2vE5q11KVg36P_EA.png" /></figure><p>This array contains the probability estimation for each example in the test set to belong to type 1. The probability values are not between 0–1 since they are not normalized. We calculated these probability values for each of the distributions.</p><pre>def predict(pdf1, pdf2, pdf3):<br> predictions = np.zeros(shape=pdf1.shape)<br> counter = 0<br> for p1, p2, p3 in zip(pdf1, pdf2, pdf3):<br> maximum = max(p1, p2, p3)<br> if maximum == p1:<br> predictions[counter] = 1<br> elif maximum == p2:<br> predictions[counter] = 2<br> elif maximum == p3:<br> predictions[counter] = 3<br> counter += 1<br> return predictions</pre><p>Our prediction strategy is simple. We will get the maximum probability value to predict the class of each training examples. If the value in pdf2 is greater than the values in pdf1 and pdf3, the corresponding example is going to be predicted as a Type 2 member.</p><pre>predictions = predict(pdf1, pdf2, pdf3)</pre><p>Let’s see how our predictions look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*FMUEHAtCz5HMCxA1S0IrHw.png" /></figure><p>It is time to measure the performance of our classifier with the accuracy metric. Accuracy is one metric for evaluating classification models. Informally, <strong>accuracy</strong> is the fraction of predictions our model got right. Formally, accuracy has the following definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*wipk_VS4gHHyxtOaO_yTsg.png" /></figure><p>Let’s calculate the accuracy of our classifier:</p><pre>accuracy = accuracy_score(predictions, y_test)<br>print(‘Accuracy of the classifier is :’, “{0:.3f}”.format(accuracy))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*7cBgDpZX0Y0hJVb-3PRnzQ.png" /></figure><p>Well done! We got %94.4 accuracy using only 2 features. If we were to use more features, we could get better results. However, if you use a lot of them, you may end up with overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*RLBqY6ZOzd3iC3akE_5ijA.png" /></figure><p>Our task is done here. I think you should get a glass of wine and celebrate it if you learned something new today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a2f7b77975" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Deep Reinforcement Learning]]></title>
            <link>https://medium.com/@erkansahin/an-introduction-to-deep-reinforcement-learning-4e6af9c5e2fd?source=rss-c03ed186b7af------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e6af9c5e2fd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Erkan Sahin]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 15:21:19 GMT</pubDate>
            <atom:updated>2019-02-10T15:21:19.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ah237aBj4JKYVrjV3qg4pQ.png" /></figure><h4><em>A brief introduction to one of the most exciting fields of Artificial Intelligence.</em></h4><p>Every living species pursues happiness in life. When you punish a child because of his actions, he feels bad and avoids doing the same thing. If you give him a smile or a little present, he will know that his action is appropriate and will continue doing the same action to be rewarded again. The same pattern applies also applies to animals. A dog learns how to act with respect to your commands by trial and error. The dog is rewarded with a hug or food when it does the right action, otherwise, the trainer punishes the animal. The dog learns what action to take for each command henceforth maximize the amount of reward. Deep Reinforcement Learning is a computer science approach that studies the design and creation of Machine Learning agents which can learn by receiving a stream of data, acting in an environment and uses trial and error method to learn.</p><p>Reinforcement Learning(RL) agents learn through interaction with the environment. Reinforcement Learning does not require labeled data as opposed to Supervised Learning and it does not need the data to be designed or collected. The learner is called <strong>agent </strong>in RL because of its dependency on interaction. In RL, a <strong>reward signal</strong> must be provided mostly. This signal is fundamentally different from labels in the Supervised Learning. The reward signal is related to achieving a specific <strong>state </strong>like reaching a location or winning the game. Most branches like Neuroscience, Computer Science and Economics want to solve the optimal action selection problem. The environment tries to reinforce or discourage certain behaviors. The agent tries to find the optimal set of actions to solve a particular problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAkIUuU4kXi8BGRE6qm2UQ.png" /><figcaption>Resource: ‘Grokking Deep Reinforcement Learning’ by Miguel Morales</figcaption></figure><p>In Reinforcement Learning, your immediate decision may affect your decisions in the feature. Being able to influence the environment makes the decision-making process much more complex. Our agent simply cannot choose the action that brings maximum immediate reward for the current state. The agent must consider the feature consequences of its actions and give its decision accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*eHdiKTzcHbkY-2rBwCGQJw.png" /><figcaption>Resource: ‘Grokking Deep Reinforcement Learning’ by Miguel Morales</figcaption></figure><h3>The architecture of a sequential decision-making problem</h3><p>In Reinforcement Learning, we have a decision maker called an agent. The agent is located in an environment in which the agent does not have total control. The role of the decision maker in this context is simple: Making decisions. First, the agent interacts with the environment. Then the environment reacts to the action of the agent. The agent receives feedback and improves something in its behavior. Actions of the agents may have influences in the environment. This makes the consequences <strong>non-deterministic</strong>. For example, when you prepare for an exam, you may not get the same result every time. Nothing can guarantee that you are going to pass or fail. Even if you study really hard, it is not certain that you are going to excel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*xdyc8o1dVlSM8YzTQ2_Lsw.png" /><figcaption>Resource: ‘Grokking Deep Reinforcement Learning’ by Miguel Morales</figcaption></figure><p>The agent may or may not have access to the exact state of the environment. For instance, if an agent plays poker, it cannot access the hand of its opponents, therefore; it has to make its decisions using its limited <strong>observations </strong>in the environment. However, in most Atari games, the agent can access the exact state of its opponent(health, abilities, limitations etc.); hence, the decision-making process becomes easier. The observation of the agent is equal to the state only if the agent has full access to the exact state of the environment. In the Poker case, the environment is partially observable; so, the agent cannot consider the exact state in its decision-making process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*bFuhKQqEoY9UECpZzbB0TQ.png" /><figcaption>Resource: ‘Grokking Deep Reinforcement Learning’ by Miguel Morales</figcaption></figure><p>In addition to the observation, the agent also receives a reward signal from the environment. The reward receives a lot of attention from the researchers. There has been recent research studying ways to make the reward depend not just on the environment, but also on something internal to the agent. It sounds exciting. We will see what is going to happen!</p><h3><strong>Why do we say Deep Reinforcement Learning rather than Reinforcement Learning?</strong></h3><p>Deep Reinforcement Learning uses multiple layers of powerful function approximators in order to solve complex sequential decision-making problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*9o6qoz7y4Bv7DArWbrleYA.png" /><figcaption>Resource: ‘Grokking Deep Reinforcement Learning’ by Miguel Morales</figcaption></figure><p>The most popular use of deep reinforcement learning (DRL), is to use deep learning to approximate the state space of large reinforcement learning problems. By doing this, we can solve RL problems that were not possible to be solved before. The most exciting development in the DRL community is a paper published by Deep Mind.</p><p>The paper introduces AlphaGo Zero, the latest evolution of <a href="https://deepmind.com/research/alphago/"><strong>AlphaGo</strong></a>, the first computer program to defeat a world champion at the ancient Chinese game of Go. Zero is even more powerful and is arguably the strongest Go player in history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*MlwJE5cDvc3WL76v_ViERw.gif" /><figcaption>Resource: Google Deep Mind</figcaption></figure><p>Previous versions of AlphaGo initially trained on thousands of human amateur and professional games to learn how to play Go. AlphaGo Zero skips this step and learns to play simply by playing games against itself, starting from completely random play. In doing so, it quickly surpassed the human level of play and defeated the <a href="http://www.nature.com/nature/journal/v529/n7587/full/nature16961.html?foxtrotcallback=true"><strong>previously published</strong></a> champion-defeating version of AlphaGo by 100 games to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Gk_SD6a2AFWq9ZPZmzU20g.gif" /><figcaption>Resource: Google Deep Mind</figcaption></figure><p>It is able to do this by using a novel form of <a href="https://en.wikipedia.org/wiki/Reinforcement_learning"><strong>reinforcement learning</strong></a>, in which AlphaGo Zero becomes its own teacher. The system starts off with a neural network that knows nothing about the game of Go. It then plays games against itself, by combining this neural network with a powerful search algorithm. As it plays, the neural network is tuned and updated to predict moves, as well as the eventual winner of the games.</p><h3>Summary</h3><p>Deep Reinforcement Learning is arguably the brightest field in the Artificial Intelligence community right now. New developments occur each day and we do not know where we are going to end up. It seems we may achieve the dream of Artificial General Intelligence in the next decades.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e6af9c5e2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>