<?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 Valdio Veliu on Medium]]></title>
        <description><![CDATA[Stories by Valdio Veliu on Medium]]></description>
        <link>https://medium.com/@valdioveliu?source=rss-65b8a4753df1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HMVVlfDiRaH5AeO2CMtKNg.png</url>
            <title>Stories by Valdio Veliu on Medium</title>
            <link>https://medium.com/@valdioveliu?source=rss-65b8a4753df1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:04:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valdioveliu/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[Flutter on steroids! Redux & MVVM architecture pattern.]]></title>
            <link>https://medium.com/@valdioveliu/flutter-on-steroids-redux-mvvm-architecture-pattern-122dda63906b?source=rss-65b8a4753df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/122dda63906b</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Valdio Veliu]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 20:47:05 GMT</pubDate>
            <atom:updated>2020-04-01T18:00:24.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bKpV4CfgIRkcwvemD8Leg.jpeg" /></figure><p>There are many approaches to developing mobile apps and by all means, this is just another one based on my opinions and best practices I’ve encountered during my work as a mobile developer. Furthermore, this solution has worked for me well and hopefully will shed some ideas on how you can structure and mold your mobile apps.</p><h3>What will we get into this article?</h3><p>This is an approach to structure large scale mobile applications with flutter build on top of the <strong>REDUX</strong> state management and implementing the <strong>MVVM</strong> (Model View ViewModel) software architecture pattern. Also, this example makes use of the singleton pattern to manage the redux store data.</p><p>By any means, this is not a step by step guide, but only a general overview of the demo app build with the previously mentioned tools.</p><p>The general idea behind this demo is to provide some kind of setup that works well for scalable applications using Flutter. Therefore most of the features and widgets are only a barebone implementation. So the focus of the app is more on the data management and organization of features while applying the MVVM architectural pattern.</p><h3>Lay down the groundwork!</h3><p>The main idea of MVVM is the separation of concerns. To separate the user interface logic from the business logic and draw a clear line between each unit of the application. Simply said the UI is only expected to do UI stuff, so display, click, scroll. That&#39;s it! 🤔</p><blockquote>Each unit has its purpose and should be concerned only to fulfill its requirements and expectations.</blockquote><p>I added a detailed explanation wiki <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/Why-MVVM%3F">about MVVM</a> to the project on what each unit of this patters is supposed to do and how the data flow is handled following the guidelines of &quot;separation of concerns&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*8KLQpzE0pP8kMtdOAFrkRA.png" /><figcaption>MVVM diagram</figcaption></figure><h3>The project structure</h3><pre>/lib<br>--/assets<br>  --/mocks<br>  --/fonts<br>--/components   #General use components (e.g. AppHeader, AppFooter)<br>--/config       #General app config files<br>--/features<br>   ../feature-1<br>   ../feature-2<br>--/models        #Data clases <br>--/store         #Contains the redux store &amp; setup.<br>  --/actions<br>  --/models      # redux related models, used to mange data inside the store.<br>  --/reducers<br>  --/view_models<br>--/template      #Used for styling and UI related data.<br>--/utils         #To store helper functions/utils (e.g. dateUtils)</pre><p>For the project structure, a feature-based approach seems to be more suited to implement the UI/VIEW part of the application. The term &quot;feature&quot; is used loosely, representing for say a separate screen of the app, but it might be several screens belonging to a sub-module. Each feature is encapsulated as its own standalone module, containing all its UI widgets. An exception here for the globally shared widgets/components between all the features.</p><p>The rest of the structure is strictly coupled to its purpose, so /models contain the MODEL classes, /store as a separate module handles all of the runtime data administration and data caching duties, /template contains styling and presentational related utils, like a <em>template</em> or <em>theme</em> of the app and so on so forth.</p><p>You can read more about it in the <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/Project-structure">project wiki</a>.</p><h3>The MVVM setup!</h3><p>I talked a bit about the VIEW part and how it&#39;s structured and its purpose, but there is a lot more to views than just clicks and scrolls 🤓 😎. E.g. how the VIEW layer is connected through the ViewModels and how to perform actions. You can read more about the types of Flutter <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/VIEWs---Flutter-Widgets">widgets and their responsibilities </a>in the wiki. Check out how the widgets are actually connected to the ViewModels and how they make use of them to access the data and request for data changes.</p><p>The MODEL portion of this patter is pretty straight forward, a bunch of classes. Well, that&#39;s not entirely true! 👀😱👀. The models need to be serializable and deserializable, convert data <strong>from</strong> JSON and <strong>to</strong> JSON since the idea is to &quot;make use&quot; of external JSON APIs and use persistence middlewares for redux to cache data in the app&#39;s memory. You can read more on <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/MODEL-classes">MODEL classes</a> and <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/Generating-serializable-models">generating serializable models</a> in the project documentation.</p><p>VIEW-MODELS?! Their purpose is to feed data to the presentational layer while encapsulating/hiding the logic behind it form the UI. In the meantime provide the VIEW layer with a way to request changes on the data-set. They are the &quot;Man in the Middle&quot; between the data and the UI. The following link explains the gist of their purpose, but still, that&#39;s not all they do. <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/ViewModel-structure">ViewModel-structure</a></p><h3>All hands on REDUX</h3><p>Redux is the main topic of this post since it was the reason that I wanted to create a working setup that is well organized in the meantime keeping its sanity and not being extra complex.</p><p>Redux is a proven state management tool in the JavaScript world, adopted by several frameworks (mostly known for React) and with different spinoffs to it, but this is a different story. 😜😜🤓</p><p>Since Flutter uses reactive-style views, same as React it makes perfect sense to use the same data management model. The redux store! This easy said than done because we have to create the structure of the store ourselves in this case since Flutter is built on Dart and it is a strongly typed language. Therefore we need to have a type for <strong>everything</strong> and not just &quot;throw&quot; stuff to the store same as in JavaScrip, no questions asked. 🙄 🤔 😳!</p><pre>/store<br>    /actions<br>    /models     # redux related models, used inside the redux store<br>    /reducers<br>    /view_models<br>  config.dart   # contains the redux store setup</pre><p>I decided to structure the store as shown above to keep a sanity over what happens in this module. So we have another set of /models in the app, but now for redux. This is where all the redux related models are stored and they represent each entry of the redux tree. Again I decided to classify them feature-based, but this does not mean that different features cannot share the same &quot;State model&quot; as I ended up calling them in the project.</p><p>The models follow the same properties as normal models presented earlier in this post, but with a very distinctive feature. The &quot;State models&quot; are created using the <strong><em>singleton pattern</em></strong> using <a href="https://dart.dev/guides/language/language-tour#factory-constructors">factory constructors</a>. This approach will avoid creating a new instance of the redux entry for every redux update.</p><p><strong>Most developers usually avoid the singleton pattern, but in this case, I found it really fitting and the perfect solution for state management in this setup.</strong></p><p>The rest of the redux setup is similar to the standard flow as in JavaScript, only the way it is implemented is what differs, and you can check that in the <a href="https://github.com/valdio/flutter-redux-mvvm/wiki/Redux-Config-&amp;-Setup">Redux Config &amp; Setup wiki</a>. Otherwise, actions are actions and reducers are reducers, same as is standard <a href="https://redux.js.org/">redux</a>.😎😎</p><p>All this fancy setup is used by the ViewModel, which can &quot;subscribe&quot; to various parts of the state and expose data to the VIEW layer also dispatch redux actions to request changes to the redux state.</p><h3><strong>Anything else?</strong></h3><p>As a matter of fact YES!</p><p>There are several topics left that are needed to make a complete setup of a native app. I covered networking and how it can be linked to redux actions so every event performed towards a ViewModel, be as it may, network-related or not, be handled in the same manner.</p><p>Another topic is Navigation. The demo presents a unified way to configure and manage routing between different screens of the app, within a custom navigation widget. Also addressing topics like, how to pass data between screens, handling NotFound states and making use to Flutter&#39;s Navigator API to transition between screens.</p><p>Anything you need to know:</p><p><a href="https://github.com/valdio/flutter-redux-mvvm/wiki">https://github.com/valdio/flutter-redux-mvvm/wiki</a></p><h3>Wrapping UP!</h3><p>The idea behind this post is not to go much into details of how everything is behind the hood, as it would take me several posts to write everything. Believe me, I tried! 😵😵 And no one wants to read several posts of technical presentations. It&#39;s too hard to follow!😅😅</p><p>Therefore, I decided to write this overview post and document everything in the project&#39;s wiki if anyone wants to read more on my logic behind the setup.</p><p>So for anyone who wants to take the project apart and learn by him/her self here si the repo. Enjoy! 🙃</p><p><a href="https://github.com/valdio/flutter-redux-mvvm">valdio/flutter-redux-mvvm</a></p><p>This project might <strong>SUBJECT TO CHANGE, </strong>as more features might be added or if nicer approaches come to mind or are suggested. I will try my best to keep everything up to date.</p><p>Issues and PRs are welcome. Happy codding! 🤘 🤓 😎<br> 📱💻 📲</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122dda63906b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin: The new Android programming language.]]></title>
            <link>https://medium.com/@valdioveliu/kotlin-the-new-android-programming-language-2be015e64ab6?source=rss-65b8a4753df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be015e64ab6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Valdio Veliu]]></dc:creator>
            <pubDate>Wed, 21 Mar 2018 18:46:19 GMT</pubDate>
            <atom:updated>2018-03-22T13:37:38.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I6e4S1HKz5SbFM0DjjxhQ.jpeg" /><figcaption>Clash of the knights</figcaption></figure><p>In the past few years, there’s been a new language taking over the Android development world: Kotlin.</p><p>One of the most significant announcements at the annual Google I/O 2017 conference was that Kotlin is a first-class language, which shocked many and raised a lot of questions and dilemmas for developers and tech enthusiasts: embrace this newly ‘knighted’ language or stand with its well-established old friend, Java?</p><blockquote>Note: I prefer not to use the term <strong>predecessor</strong>, as referred by many, when comparing Java to Kotlin, because Java is still very much alive and well within the Android community, even after the big announcement.</blockquote><p>Even if Kotlin tried to completely replace Java in Android, it’s not so easy to roll-out to a new language in no time. The process requires time and usually elapses over many years. However, this is not the case! Kotlin presents itself as a better alternative for Android, not a replacement. <em>At least for now!</em></p><h3><strong>Language Background</strong></h3><p>The Java programming language has been around since the 90’s. Chances are, if you’re a tech-savvy person or know something about programming, you’ve at least heard about Java.</p><p>I know what you are thinking. “The 90&#39;s? Wow, that’s old! Why do people still use it in development? Shouldn’t it be in a museum?”</p><p>On the contrary, when it comes to programming languages, sometimes older is better; with more time, more improvements tend to happen.</p><p>Kotlin, on the other hand, has only been around since 2011. That’s not much when compared to “Java standards”, but that’s a mature enough language to be considered.</p><p>Does that mean Java is better than Kotlin because it’s more mature?</p><p>No, not necessarily. Kotlin might be newer than Java, but it isn’t new and has also evolved. Plus, it’s adopted some of the best features from the top-level languages.</p><h3><strong>What’s All the Fuss About Kotlin?</strong></h3><blockquote><strong>Is it true that Kotlin is better than Java?</strong></blockquote><p>Koltin, being a modern language and all, surely has taken into practice the best features of the languages around. On the contrary, Java has had to invent its features. Some of which Koltin has adopted.</p><p>There is no denying the fact that Java is more verbose; Kotlin removes a lot of boilerplate code. In this aspect Kotin is more superior, leading to smaller development time for Android apps. But, is that all that Kotlin has to offer?</p><p>To stand in Java’s defense, the fact the Java is old and more verbose is not at all true. On the contrary, Java is as full featured as Kolin and many other top of the line languages. The hiccup is only in Android! In Android, we are stuck with Java 7.</p><p>Not Being able to use Java 8 limits developers to fully express the language capabilities. Not counting here that Java 9 is the official version since September 2017.</p><p>This is not entirely true. Because, alongside making Kotlin an official language, Google announced Java 8 support for Android development. That’s great! There are many language features that can make the development enjoyable in Java 8. Unfortunately not all Java 8 features are supported for older devices.</p><p>For example, you are now able to use <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda expressions</a>, <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method References</a> and a few other language features down to API level 9, Android Gingerbread. But we are not so lucky with some other features, which available only on API level 24 or higher, Android Nougat and Oreo. If you are targeting the ‘power users’ of the Android OS, you are in luck with Java. But for many other developers, myself included, limiting apps to work only on devices running Android Nougat, Oreo and the new mysterious Android P, is not an option.</p><p>If you want to learn more on the mater check out the <a href="https://developer.android.com/studio/write/java8-support.html#supported_features">supported Java 8 language features and APIs</a>.</p><h3><strong>Java and Kotlin, how do they fit together?</strong></h3><p>Despite what language you chose as an Android developer, I believe one question comes to mind! What changes in the development process from Java to Kotlin?</p><p>In “traditional” Android, I mean with Java, we are used to lifecycle methods. The main building blocks of Android apps like Activities, Fragments, Services, etc are built upon the component-based development paradigm. The component-based approach has lifecycle methods in the core of the development process. Kotlin uses the same approach in development. It uses the same components and the same lifecycle methods as Java does. Just a little “sugar” added to the code.</p><p>This lets the two languages to have interoperability between each other. This is probably one of the best features they both share; these languages are interchangeable. And certainly being able to interoperate both these languages is a great thing. You can migrate a project to Kotlin at any time, module by module.</p><p>Kotlin, having the same development style as Java helps even Java developers to easily transition into this new language, if they so desire. So the transition is not at all painful for a Java developer to get around in a Kotlin project. Most of the things are left unchanged, except the language syntax.</p><p><strong>Here is the prof !</strong></p><p>The most famous lifecycle method in Android Activities is the onCreate() method. If you have never seen Kotlin code before and you see the onCreate() method in this language what will you think?!</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>   super.onCreate(savedInstanceState)<br>   setContentView(R.layout.activity_main)<br>}</pre><p>Well, there is not much difference there except a bit of sugar syntax. In contrast form Java, Kotlin specifies it as a function. It does not use the @Override annotation. That’s cleaner! The “protected void” keywords before onCreate are unnecessary before this lifecycle method. The rest looks the same, except the question mark at the end of the method parameters. Well, that’s a language construct for NULL safety!</p><p>As I come from a Java background in Android, I don’t see anything confusing so far!</p><p>The fact that Kotlin is inspired by top language designs of today makes it so similar to many languages. So it is not only easy to transition from Java to Kotlin but even if you have other backgrounds and want to try Kotlin in Android.</p><h3><strong>Main language differences</strong></h3><p>Besides being used for the same development purpose, both these languages have a few key differences that differentiate them from each other. These differences are mainly related to language design features leading to ease of development. Further on this post, I will go through some of the key turning points where each of these languages shines.</p><p>So, let’s lay out the ground with what Koltin has to offer and see if Java can keep up!</p><h4>No constraints in programming philosophy</h4><p>If we know one thing about Java is that Java is an Object Oriented Language (OOP). On the other hand Kotlin, being a modern language, makes use of the latest language design patterns. This means that you are not strict to only use object-oriented programming. If it suits you better, you can choose between OOP and functional programming, <strong>to a certain extent</strong>. If you come from a functional programming background you will love this language feature.</p><p>There are a lot of praised features of Kotlin in the development community. Features like NULL safety are more praised than choosing your own programing philosophy. That truly is an amazing feature to have, but choosing your own development style is far more important, at least in my opinion.</p><p>You are not bound by the language constraints in order to develop software. You can choose the paradigm that suits you best. Unfortunately, in Java, we can’t do that. In Java, OOP is the “King” and the “King” gives the orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uL-1ScNdP_dxNk5pFADu7w.jpeg" /></figure><h4>Reducing boilerplate code</h4><p>One of the great advantages of Kotlin is the fact that it has a polished syntax and language design. Therefore some of the features that Java has had to develop over time, Kotlin has taken for granted and are included from its early releases. This leads to the big gap missing in Android between Java 7 and 8 as I mentioned earlier.</p><p>A nice example of boilerplate code removed by using Kotlin are Data classes. In Kotlin, we can declare a class and all its properties in a single line. Imagine all the getters and setters you are used to in Java gone. I will get into Data classes in more detail later in this article.</p><h4>Null safety</h4><p>Null-safety is one of the biggest setbacks of working with Java. You don’t ever, ever escape the infamous <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html">NullPointerException</a>, the billion dollar mistake. This is one of those things that will ‘haunt’ Java developers forever.</p><p>So imagine what Kotlin developers brag about when they talk about Java. That’s right, it’s Null safety!</p><p>There is not denying that NULL safety is amongst the best features this new language offers. So say goodbye to the old NullPointerException. Furthermore, this language offers the possibility to declare variables nullable by choice. What do I mean with this?</p><p>Kotlin has solved this problem by making all types of variables non-nullable by default. The compiler won’t let you use a non-initialized, nullable variable. But, if you want a null variable at all costs, you have to declare it at such.</p><p>Here is a code sample on how to initialize variables in Kotlin:</p><pre>var name: String = &quot;Name&quot;<br>var nullString: String? = null</pre><p>Whereas in Java you can write:</p><pre>String name = null;</pre><p>and nothing in the world will stop you.</p><h4>Lambda expressions</h4><p>I mentioned a bit before that come Java 8 in Android, we can now use Lambda expressions. Lambda expressions are a simple way of expressing functional interfaces, simply said, interfaces with a single method.</p><p>So where do you use them? Well, the most common place you can use lambda expressions is for onClick listeners. Here is how we set an onClickListener to a button in Java.</p><pre>button.setOnClickListener(new View.OnClickListener() {<br>             public void onClick(View v) {<br>                 <em>// Handle onClick</em><br>             }<br>         });</pre><p>And by using lambdas we end up getting the following.</p><pre>button.setOnClickListener(view -&gt; { <br><em>// Handle onClick</em><br>});</pre><p>By using Java 8 we surely get this great and cleaner way to handle onClick events, but with Kotlin this feature out of the box, no questions asked. Everything is cleaner and more polished.</p><h4>Higher-order functions</h4><p>If you are familiar with JavaScript you definitely know about <a href="https://kotlinlang.org/docs/reference/lambdas.html#higher-order-functions">higher-order functions</a>. By definition, a higher-order function is a function that can take other functions as an argument, or can return a function as a response. Another great feature about Kotlin is the ability to use this paradigm in development. So transitioning from JavaScript to Kotlin will not be a complete stranger to you.</p><p>If you are wondering why are higher order functions a big deal, let’s work through an example in which this language feature shines.</p><blockquote>Example of a higher-order function</blockquote><p>Imagine having to do a network call. A network call can return a specific set of data or an error code if the request fails.</p><p>By using Kotlin, we can make a function for the network call and pass as its parameters two callback functions, one for success and one for the failure of the request. We create something that resembles the following code.</p><pre>someNetworkCall(response -&gt; {<br>    	<em>// perform some action with the response</em><br>}, failure -&gt; {<br>    	<em>// handle failure</em><br>});</pre><p>Whereas in Java this whole process is a bit more complex. We have to have an interface and pass an instance of that interface to handle the network call. This requires more code. Here is an example.</p><pre>public interface ResponseCallback {<br>    void onResponse(ResponseType response);<br>    void onFailure(Exception ex);<br>}<br>someNetworkCall(new ResponseCallback () {<br>    public void onResponse(ResponseType response) {<br>        <em>// perform some action with the response</em><br>    }<br>    public void onFailure(Exception ex) {<br>        <em>// handle exception</em><br>    }<br>});</pre><p>Surely this is only the template of the someNetworkCall method and to make it work you have to implement it, in both cases. As you can clearly see the process requires far more code with Java. And if you didn’t notice, in the Kotlin example we even utilized Lambda expressions, mentioned in the previous sections, to make the code cleaner and compact. If you want to learn more about this features, make sure to check out the <a href="https://kotlinlang.org/docs/reference/lambdas.html#higher-order-functions-and-lambdas">Higher-Order Functions and Lambdas</a> in the Kotlin documentation.</p><h4>Coroutines</h4><p>Usually, working with complex operations in your app are quite expensive for the application thread. For this reason, expensive operations are handled asynchronously in order to avoid blocking the main thread of the application.</p><p>In the general case, and what is suggested by Android engineers, the main thread of the application should be used for manipulating the UI and small data operations. If you follow this pattern in development, the app you are building will work seamlessly and without freezing or crashing (App not responding issue). To be fair, this is more a problem in older devices or in devices with low resources, but why not to keep everything performant.</p><p>In Java, the easiest way to perform operations asynchronously is to use <a href="https://developer.android.com/reference/android/os/AsyncTask.html">AsyncTasks</a>. Usually, you create a new class that extends AsyncTask and then perform the operation, but this results in too much boilerplate code.<br>However, Kotlin in its 1.1 release presents Coroutines. Same as AsyncTask, Coroutines are used to perform asynchronous tasks without blocking the main thread of the application. What you benefit from Coroutines is, less boilerplate code and they are very lightweight. So they will have little to no impact on the app’s performance even if you run multiple Coroutines at the same time.</p><p>The construct of a Coroutine is really simple. The launch function is used to run a coroutine.</p><pre>launch {<br>    <em>//...</em><br>}</pre><blockquote>Example of a Coroutine</blockquote><p>Let’s see Coroutines in action. The following function prints some messages in the console. To make sure that the Coroutine truly runs asynchronously I added a delay of 4 seconds inside it. That should print the message inside the Coroutine after both the other messages are printed, non-blocking execution.</p><pre>fun testCoroutines() {<br>   println(&quot;Before coroutine&quot;)<br>   launch {<br>       delay(4000)<br>       println(&quot;Inside coroutine&quot;)<br>   }<br>   println(&quot;After coroutine&quot;)<br>}</pre><p>The output of this function will be:<br>→ Before coroutine<br>→ After coroutine<br>And 4 seconds latter:<br>→ Inside coroutine</p><blockquote>Just a note here: In order to use Coroutines in Android you have to add some extra configurations to the project. Just follow this <a href="https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html">introduction to Coroutines</a>.</blockquote><h4>Type aliases</h4><p>Another cool feature that came around with Kotlin 1.1 is Type aliases. They can be used to provide alternative, shorter, meaningful names for existing types. This language feature, despite being quite small and not so meaningful can prove to be quite useful.</p><p>In the following code snippet, you can find a basic example of a login function.</p><pre>typealias Username = String<br>typealias  Password = String<br>fun loginUser(username: Username, password: Password) {<br>   <em>//login operation</em><br>   println(&quot;Logged in as &quot; + username)<br>}</pre><p>It’s true that the provided example is pretty basic and it’s not necessary to use Type aliases. We usually are interested to use Type aliases with more complex data structures. Here is an example:</p><pre>typealias SubscibedClasses = Map&lt;String, ArrayList&gt;</pre><p>Imagine the following scenario. In a school, we have some students we are interested in. Each of the students is subscribed and attend different classes. Now, we are interested to have a data collection of all the classes that each student attends. We can represent this data structure as a Map object that has as a String key, let’s say the student’s ID, and as a value an ArrayList of the classes that each student attends. Keep in mind that a Map is a collection that holds pairs of objects (keys and values).</p><p>Now that we have this Map we need a shorter way to remember it, for different reasons. Because there can be different types of similar data collections in our app and we can get easily mistaken when referencing them. So, if we use Type aliases, like in the example above, we are sure that we are referencing the right data collection and it’s easier to remember.</p><h4>Data Classes vs Java regular classes</h4><p>Most apps today are data-driven. Therefore we find ourselves creating classes with many data fields, using primitive data types and even collections like Lists, ArrayLists, Maps, etc.</p><p>In Java, you have probably heard about the terminology POJO. POJO stands for “Plain Old Java Object”.</p><p>A POJO is a pure data structure with different fields, getters and setters for this data fields. If needed it might contain some overridden methods from the Object superclass. At least this is what we relate to in Java where everything is written by hand. If you utilize the capabilities of your development tools you can even auto-generate all the getters and setters in Android Studio. But still, that’s a lot of boilerplate. The same story repeats every time when creating a POJO.</p><p>Kotlin, on the other hand, presented a more modern approach to this problem. I mentioned this fact a bit before when talking about boilerplate code. In Kotlin, we can declare a class and all its properties in a single line. This is achieved by utilizing the <a href="https://kotlinlang.org/docs/reference/data-classes.html">Data class</a> concept provided by the language.</p><p>But what if I want to access a specific field of the class? Don’t worry! The compiler got you covered. It will generate all the getters and setters you need to access specific fields in the class, it even will generate the helper functions like toString() and a copy(). Check out the <a href="https://kotlinlang.org/docs/reference/data-classes.html">Data class</a> documentation for more.</p><blockquote>Sample Data class vs Java regular classes</blockquote><p>For example. Here is the correspondent Data class of this traditional Java POJO.</p><pre>public class User {<br>   private String email;<br>   private String password;<br>   public String getEmail() {<br>       return email;<br>   }<br>   public void setEmail(String email) {<br>       this.email = email;<br>   }<br>   public String getPassword() {<br>       return password;<br>   }<br>   public void setPassword(String password) {<br>       this.password = password;<br>   }<br>}</pre><p>All this boilerplate is converted into a single liner.</p><pre>data class User(var email: String, var password: String)</pre><p>The difference is obvious.</p><h3>Common Grounds</h3><p>Up until now, I’ve covered the advantages of Kotlin, but there are not only advantages that Koltin has over Java. There are some common featured both of them share.</p><h4>Kotlin a JVM language</h4><p>Kotlin is a JVM (Java Virtual Machine) language, so it can run anywhere there is a JVM present. So, not only in Android but the focus of this article is the Android ecosystem. Like Java, Kotlin compiles into bytecode and runs through a virtual machine, the JVM.</p><p>That said, compiling Java or Kotlin code for Android provides native applications. So after all, Koltin still runs on top of Java code! Therefore, it’s safe to expect the same performance when running Android apps.</p><p>That’s true, and false! It’s true that Kotlin apps are compiled into native bytecode and run on the same JVM that Java apps do. It’s false because there is a bit of overhead included by the Kotlin standard library which is added to the project.</p><h4>Interoperability</h4><p>Finally, we are covering the most common ground these languages share.</p><p>As I mentioned before, interoperability between these languages is an amazing characteristic they share. This means that we are able to seamlessly use code from both languages in the same project.</p><p>The end result will be the same bytecode when running apps in Android. That’s why we take the interoperability between this languages so lightly because they both compile into native applications.</p><h3>Language design apart!</h3><p>Up until now, I focused more on language features, what each language brings to the table in the development perspective. But what about productivity and business perspective? Which will be a better choice for today’s development requirements?</p><p>It is pretty obvious that the choice is Kotlin. This is mostly due to the modern language design. Kotlin being a modern language has adopted all the modern and well-tested features of existing languages. That said, we achieve a tremendous increase in productivity. Software gets delivered faster and with fewer bugs in the overall product. The same can not be said for Java, unless the software goes through rigorous testing.</p><p>I have read that many developers and myself included considering Kotlin to be Java with “sugar syntax”. So, Kotlin does increase the efficiency and makes the programming more enjoyable. After all, the modern world is in more demand for products and product features than in highly technical skills, at least that’s true in most cases.</p><p>Simply said, what we gain by using Kotlin we can summarise in:</p><p>– Lower development time, increase in productivity<br>– Easy to maintain overall product<br>– Fewer bugs in overall product<br>– Less code<br>– Easy migration from Java to Kotlin</p><h3>But does that put Java “out of a job” in Android?</h3><p>That’s not true at all! Java is still widely used in Android. It has a better tool support, as it has been around far more than Kotlin.<br>Also if you are a performance freak, Java is about 25% faster than Kotlin in Gradle build-time, due to the fact that we include the Kotlin standard library to compile Kotlin files.</p><p>At the end of everything, Kotlin compiles to bytecode in order to run on Android devices, so there is a bit of Java hidden somewhere :].</p><p>Furthermore, it’s not uncommon to have both these languages in the same project. Developers, extensively use Java existing libraries in Kotlin projects, not just for sentimental reasons, but Java libraries have been extensively tested and are proven to work.</p><h3>Closing thoughts</h3><p>Here we come to a conclusion. Some may be still in a dilemma, Java or Kotlin! Surely, with Kotlin we gain productivity and development pleasure, but Java is more “deeply rooted” in the Android ecosystem. And there is the slight performance issue. Java is a bit faster and provides smaller application files.</p><p>In the ease of development surely Kotlin has a large advantage over Java. And if you want to have “a free hand” in developing software Kotlin can allow you to chose your own programing philosophy.</p><p>In the end, its all up to the developer to chose.</p><p><strong>Which would you choose?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be015e64ab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Bridge with Kotlin]]></title>
            <link>https://proandroiddev.com/react-native-bridge-with-kotlin-b2afde2f70b?source=rss-65b8a4753df1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2afde2f70b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Valdio Veliu]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 18:57:05 GMT</pubDate>
            <atom:updated>2018-01-25T10:12:33.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5b7ZyxKrxOykyzGwsOAiw.jpeg" /></figure><p>React Native, despite being one of the most preferred cross-platform in mobile development, has its limitations too. There may be some features that are not implemented yet in React Native or some device-specific features that are not supported by this development platform. So we can use native modules to fill the gap.</p><p>Why do we need native modules in React Native apps?</p><p>Who can really say! Maybe you want to make platform-specific code or want to reuse some existing code. For whatever the reason, React Native allows you to create your own native modules and expose them to JavaScript. The whole process is described in depth in the <a href="http://facebook.github.io/react-native/docs/native-modules-android.html">Native Modules Android documentation</a>.</p><p>If you want to get acquainted with the technical part of the topic, I strongly suggest you read the documentation first. As they explain in detail each step in which native Android modules are exposed to React code.</p><p>In the documentation, you can find a detailed example of how to bridge native Java modules to React Native. But what about <strong>Kotlin</strong>? Since Google I/O 2017, Kotlin is to a first-class language in Android.</p><p>In this post, I will focus on one question.<strong> How to bridge native Kotlin modules and UI components to React Native apps?</strong> So here we are! Lets bridge Kotlin to React Native.</p><p>Keep in mind that in the post I will focus on the Android side of the app. This is not an ultimate guide into native module bridging in IOS and Android. Rather, I will go through step by step the process needed to compile Kotlin code as native modules in React Native projects. And since the React Native build versions are a bit outdated, there will be quite a few changes in the build files of the Android project until we finally get to the Kotlin code.</p><p><strong>Are you feeling lazy? Jump right to the final project.</strong></p><p><a href="https://github.com/valdio/ReactNative_Kotlin_Bridge">valdio/ReactNative_Kotlin_Bridge</a></p><h3>Create a new React Native project</h3><p>I will go through using the <a href="https://facebook.github.io/react-native/docs/getting-started.html#the-react-native-cli">react native CLI</a> commands, but if you prefer to use Expo the process is the same. Just create a new app and run it on your device.</p><p>Let’s start by creating a new project. Open your terminal, <em>cd</em> to your development folder and create a new project.</p><blockquote>react-native init ReactNative_Kotlin_Bridge</blockquote><p>After the project is created, <strong>cd </strong>into the projects folder and run the app in your Android device.</p><blockquote>react-native run-android</blockquote><p>Make sure your app works properly.</p><h3>Including Kotlin to the project</h3><p>Now that the react Native app is created we like to include Kotlin to the android project.</p><p>Open the project in your text editor and navigate to your android project. I will be using Atom as my editor in this example, but I strongly suggest you open the android section of this project in Android Studio. What Android Studio will provide, is perfect indexing of the project and if you have some missing packages and dependencies it will suggest to install them. Since we are going to add some extra packages in the project Gradle files, you will definitely have some packages to install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*HyCXDCkncdiVCRUTzrMdrA.png" /><figcaption>Android folder structure</figcaption></figure><h3>Add Kotlin to the Gradle build files</h3><p>There are quite a few changes to be made in the project in order to run Kotlin code.</p><p>Lest start by editing the<em> </em>build.gradle file at the project level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*8K19b24y6lxfd0N9nodZFw.png" /><figcaption>Project level <em>build.gradle</em></figcaption></figure><p>At this time React Native uses an outdated Gradle build version. On the other hand, the latest Gradle version available at this time is version 4.1. Therefore I am going to update the Gradle version.</p><p>If you have any problems with the change in the Gradle version check out the tutorial on how to <a href="https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html">Migrate to Android Gradle 3.0.0</a>. This Gradle version has a far superior build speed than its predecessor, so why not ease our life with faster builds.</p><p>Open the project-level build.gradle and make the following changes.</p><p>Include the Kotlin version:</p><pre>buildscript {</pre><pre>  ext.kotlin_version = &#39;1.2.10&#39;</pre><pre>  //...</pre><pre>}</pre><p>Make sure to add google() in the buildscript.repositories</p><pre>buildscript{</pre><pre>  repositories {</pre><pre>    google()</pre><pre>    //...</pre><pre>  }</pre><pre>}</pre><p>Also, add google() in allprojects.repositories</p><pre>allprojects {</pre><pre>  repositories {</pre><pre>    //...</pre><pre>    google()</pre><pre>  }</pre><pre>}</pre><p>Upgrade the build tools version to 3.0.1 and add the following classpath in the dependencies to include the Kotlin Gradle plugin .</p><pre>dependencies {</pre><pre>  classpath &#39;com.android.tools.build:gradle:3.0.1&#39;</pre><pre>  classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;</pre><pre>}</pre><p>If you have other dependencies make sure you add them to.</p><h3>Upgrade Gradle version</h3><p>Since we are upgrading our Gradle version, in the Gradle section of the project we are upgrading to Gradle 4.1. Make sure you open the “<strong>gradle” </strong>folder and not “<strong>.gradle”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*BZyS4VV4p8zhWMGieQX9Wg.png" /><figcaption>Upgrading the Gradle version</figcaption></figure><p>Open gradle-wrapper.properties and edit the distributionUrl</p><p>Replace the following line:</p><pre># distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip</pre><pre># Replace with: </pre><pre>distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip</pre><h3>Application modules build.gradle (app)</h3><p>Now that we upgraded the build tool version, its time to include Kotlin to the project. <strong>FINALLY!</strong></p><p>Open build.gradle (app) and we have to make a few changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*vY4JTu0x7vq7hpiqQFsysw.png" /><figcaption>Include Kotlin to the project</figcaption></figure><p>At the top of the file, include the following Kotlin plugins.</p><pre>apply plugin: &quot;com.android.application&quot; // already exists in build.gradle</pre><pre>apply plugin: &quot;kotlin-android&quot;</pre><pre>apply plugin: &quot;kotlin-android-extensions&quot;</pre><p>In the dependencies section add the following dependency</p><pre>dependencies {</pre><pre>implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version&quot;</pre><pre>//...</pre><pre>}</pre><p>After you have followed all this steps, now you can test your app.</p><p><strong>cd </strong>into the project folder and run the React Native app. <strong>Don’t just hot-reload the app.</strong></p><p>Run in the terminal:</p><blockquote>react-native run-android</blockquote><p>Sometimes the command fails for some reason! I’m not quite sure why! Just run it a few times so the project can sync with the new gradle version.</p><p>It might take a while as the Android project will sync with the new Gradle version and will download all the missing packages and dependencies. If the project runs successfully you are in luck. And for some reason the project doesn&#39;t run successfully, you might have some missing dependencies or SDK packages. To make the fixes, open the android folder of the React Native project using Android Studio and sync the Gradle from there. It will show all whats wrong with your project and give you suggestions on how to fix the issues. Just sync everything and fix the project and you are good to go.</p><h3>We can now bridge Kotlin in React Native. Yea!</h3><p>Finally, here we are! We can run native Kotlin code in our project. I’m assuming you read the React Native article on <a href="http://facebook.github.io/react-native/docs/native-modules-android.html">native modules in Android</a> that I mentioned before. In the post, it explains that native modules usually extend the ReactContextBaseJavaModule class and implement the required functions required by JavaScript to bridge to this modules. Also in Android, native modules have to be registered in order to be accessed by JavaScript.</p><p>On the documentation you will find an example on how to create a native Java Toast message in Android. If you are familiar with that example, I migrated the complete Java example into Kotlin code. You can find the native Kotlin module on the<a href="https://github.com/valdio/ReactNative_Kotlin_Bridge"> final project on Github</a>. The explanation about the methods is the same as in the documentation. So you wont have any difficulties if you want to follow along with the same example featured in the documentation. Also, I kept the function and class names same as in the documentation example.</p><p>Further on in this post, I will cover another example on how to run native Kotlin Activities by using the React Native native module bridge. I created a video stream Activity, completely written in Kotlin that plays a video at a provided URL. Since we want to utilize the native module bridge, I am going to pass the streaming URL and the video title from React Native. The VideoStreamingActivity will play the video and display its title. This is not a complex Activity, as I wanted to keep things simple and focus more on creating the native module bridge.</p><h3>Kotlin Hands on!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*iyCxDocMVWIBnF23f1nS5g.png" /><figcaption>Creating the Kotlin video stream Activity</figcaption></figure><p><strong>It’s time to write some Kotlin.</strong><br>Now that we created the React Native — Kotlin bridge it’s time to put it to a test. So let’s start by creating three Kotlin classes. Create a folder inside the project package, KotlinVideoStreaming.</p><p>Inside the KotlinVideoStreaming folder create the following files. Kotlin files end with ‘<strong>.kt</strong>’.</p><p>→ <strong>VideoStreamingActivity.kt</strong> // the video streaming activity</p><p>→ <strong>StreamPackage.kt</strong> // used to register the native module</p><p>→ <strong>StreamManager.kt</strong> // used to start the Kotlin Activity and implement the getName() function</p><p>In the res folder create the folderlayout , because it is not present when creating the React Native app. Inside that folder create a layout file for the activity.</p><p>→ <strong>activity_video_streaming.xml </strong>// layout file for VideoStreamingActivity</p><p>Inside this layout file add the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b6324d625dc81617640bc2b0743a33/href">https://medium.com/media/f4b6324d625dc81617640bc2b0743a33/href</a></iframe><p>Inside the VideoStreamingActivity file pase the followin code for the Activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c5018100dd81c3383b1d94e1e765f32/href">https://medium.com/media/7c5018100dd81c3383b1d94e1e765f32/href</a></iframe><p>Don’t focus too much on the code, the main objective here is testing the Kotlin native module. The Activity expects two strings passed through the intent containing the streaming URL and the video title. The rest of the code is related to the video stream functionalities. <br>If you are following along with a different package name, make sure you update the one already provided in this class. The same is true even for the other two classes.</p><p>Next step is to register the activity. Open AndroidManifest.xml and add the following code alongside the other Activities generated by React Native.</p><pre>&lt;activity android:name=&quot;.KotlinVideoStreaming.VideoStreamingActivity&quot; /&gt;</pre><p>In the StreamManager file paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cbd323973c120ed29bedc7f19413c0/href">https://medium.com/media/20cbd323973c120ed29bedc7f19413c0/href</a></iframe><p>This class implements the necessary functionalities to run the native module and implements the getName() function which registers the native Kotlin module with the React Native bridge.</p><p>In the StreamPackage file paste the follwoing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d4c79185007bceec5b6475af5ef24f/href">https://medium.com/media/48d4c79185007bceec5b6475af5ef24f/href</a></iframe><p>This class is used to register the native module with the application. So we now head out to MainApplication.java to register the module. In MainApplication.java, first of all, add the import of the video stream module.</p><pre>import com.reactnative_kotlin_bridge.KotlinVideoStreaming.StreamPackage;</pre><p>Then, we have to register the Kotlin module to the getPackages() method. Like the following:</p><pre>@Override</pre><pre>protected List&lt;ReactPackage&gt; getPackages() {</pre><pre>  return Arrays.&lt;ReactPackage&gt;asList(</pre><pre>    new MainReactPackage(),</pre><pre>    <strong>new StreamPackage()</strong></pre><pre>  );</pre><pre>}</pre><p>That’s it! We are all ready to go from the Kotlin part.</p><p>Now let’s make use of the Kotlin module. In React native create a new file, KotlinVideoStream.js and paste the following code:</p><pre>import {NativeModules} from &#39;react-native&#39;;</pre><pre>module.exports = NativeModules.KotlinVideoStream;</pre><p>This will import the module and we can now use it in the app like the following example.</p><pre>import KotlinVideoStream from &#39;./KotlinVideoStream&#39;;</pre><pre>//...</pre><pre>KotlinVideoStream.playVideoStream(</pre><pre>  &quot;Title&quot;,</pre><pre>  &quot;StreamURL&quot;</pre><pre>);</pre><p>In React Native we can now call the exposed method in the StreamManager class, playVideoStream() through which we can utilize our Kotlin module.</p><h3>Conclusions</h3><p>Thank you for reading this far. If you are having trouble configuring the project yourself, check out the <a href="https://github.com/valdio/ReactNative_Kotlin_Bridge">final project on Github</a>. In the final project, I also included the Kotlin Toast module featured in the react documentation.</p><p>Have a look at the final app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgeSQXGukv48%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgeSQXGukv48&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgeSQXGukv48%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e729a870e732eeedd71dac57144172b4/href">https://medium.com/media/e729a870e732eeedd71dac57144172b4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff20c9a%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Ff20c9a%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Ff20c9a%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href">https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2afde2f70b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/react-native-bridge-with-kotlin-b2afde2f70b">React Native Bridge with Kotlin</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>