<?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 Lunabee Studio Dev on Medium]]></title>
        <description><![CDATA[Stories by Lunabee Studio Dev on Medium]]></description>
        <link>https://medium.com/@lunabee-studio-dev?source=rss-38f574390867------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*pNjPE9XXz4pd52wWNbEw4w.png</url>
            <title>Stories by Lunabee Studio Dev on Medium</title>
            <link>https://medium.com/@lunabee-studio-dev?source=rss-38f574390867------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:24:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lunabee-studio-dev/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[Build a form with Jetpack Compose, a better use of the state]]></title>
            <link>https://lunabee-studio-dev.medium.com/build-a-form-with-jetpack-compose-a-better-use-of-the-state-bd3ca218a354?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3ca218a354</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Fri, 12 May 2023 09:58:53 GMT</pubDate>
            <atom:updated>2023-05-12T09:58:53.430Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal of this article is to show you a way to implement a form with inputs. We will present a simple method to handle the state of the form and make sure it survives configuration changes</p><p><strong>This is our objective👇</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*YwEuPW_hojE5bPdM83ySeQ.png" /></figure><h4>Let’s implement the UI of the screen : 📱</h4><p>We can take our keyboard and start to write our compose screen ! 🧑‍💻</p><pre>@Composable<br>fun LoginScreen() {<br><br>    Column(<br>        horizontalAlignment = Alignment.CenterHorizontally,<br>        verticalArrangement = Arrangement.spacedBy(16.dp),<br>        modifier = Modifier<br>            .padding(horizontal = 16.dp, vertical = 24.dp)<br>            .imePadding()<br>    ) {<br>        Text(<br>            text = &quot;Hikes&quot;,<br>            style = HikesTheme.typography.header<br>        )<br><br>        Image(<br>            painter = painterResource(id = R.drawable.hiking),<br>            contentDescription = null,<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .weight(1f)<br>        )<br><br><br>        OutlinedTextField(<br>            value = &quot;&quot; ,<br>            onValueChange = {},<br>            placeholder = { Text(text = &quot;Email&quot;) },<br>            modifier = Modifier.fillMaxWidth()<br>        )<br><br>        OutlinedTextField(<br>            value = &quot;&quot; ,<br>            onValueChange = {},<br>            placeholder = { Text(text = &quot;Password&quot;) },<br>            modifier = Modifier.fillMaxWidth()<br>        )<br><br>        Button(onClick = { }) {<br>            Text(<br>                text = &quot;Login&quot;,<br>                style = HikesTheme.typography.action<br>            )<br>        }<br><br>    }<br>}</pre><p>The code above allows us to display the login screen required. But if you try to use the text inputs, you will notice that there is something wrong… 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*_UWP5cQP_pYMFBoKpmncbg.gif" /></figure><p>The textfields do not register our inputs, but don’t worry there is a perfectly rational explication to this phenomenon 😉</p><pre>OutlinedTextField(<br>    value = &quot;&quot; 👈 ⚠️,<br>    onValueChange = {}, 👈 ⚠️<br>    placeholder = { Text(text = &quot;Email&quot;) },<br>    modifier = Modifier.fillMaxWidth()<br>)</pre><p>Our current implementation is missing a key element<strong> : the state !</strong></p><p>By making the UI react to a state change, Compose introduced a new way of building screens. When <em>thinking in compose</em> the state is at the heart of our reflexion. <strong>If we do not update the state, our UI will never change.</strong></p><h3>Naive state</h3><p>Compose is <strong>declarative</strong>, it means that in order to update themselves, our composables need to observe for changes in a state.</p><p>One of the easy way to create a state is to use a remember associated with a MutableState</p><pre>var email: String by remember { mutableStateOf(&quot;&quot;) }</pre><p>We can now use that email variable in our textfield 👇</p><pre>OutlinedTextField(<br>    value = email,<br>    onValueChange = { value -&gt; email = value },<br>    placeholder = {<br>        Text(text = &quot;Email&quot;)<br>    },<br>    modifier = Modifier.fillMaxWidth()<br>)</pre><p>As you can see, we pass the email as a value to our textfield, we also update it using a lambda in the onValueChange parameter.</p><p><strong>By doing that the user can now enter its email and password 🎉</strong></p><p>However, our current implementation will allow us to remember the values of the email and password <strong>as long our entire screen is not recomposed</strong>, and it is exactly what happens during a configuration change :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*FoK2BF-MYgp79tzOwagw8A.gif" /></figure><p>If the user switch from light to dark mode or perform a device rotation, our state is not remembered which can be very frustrating. Hopefully for she/him, there is something that will fix our issues.</p><h3>RememberSaveable to the rescue</h3><p>As we’ve seen, using remember will not retain state across configuration change, however, rememberSaveable will save the value in a Bundle that will survive theses config changes.</p><p>For that, we just need to replace our remember by rememberSaveable</p><pre>var email: String by rememberSaveable { mutableStateOf(&quot;&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*xist2pZe_9OZi3iqSvp8oQ.gif" /></figure><p><strong>Our state now survives recomposition 🥳</strong></p><p>But what if our state needs to hold a lot of information (like a big form for instance) or need to save custom data ? Having a lot of rememberSaveable declaration doesn’t seem very optimal and will alter the clarity of the code.</p><h3>Implementing a custom composable state</h3><p>The advantage of creating a custom state is that we will have a state that really matches our need.</p><p>For our screen we need to save the <strong>email</strong> and the <strong>password</strong> (for now 😉)</p><pre>class LoginScreenComposableState {<br>    <br>  var email: String by mutableStateOf(&quot;&quot;)<br>        private set<br>  var password: String by mutableStateOf(&quot;&quot;)<br>        private set<br><br>  fun updateEmail(newValue: String) {<br>      email = newValue<br>   }<br>  <br>  fun updatePassword(newValue: String) {<br>      password = newValue<br>  }<br>}</pre><p>Now that we have defined what data our custom state will hold, we need to create a custom Saver for it. To put in simple terms, the role of this saver is to describe how the LoginScreenComposableState can be converted into something Saveable. We will need to provide a map of Key,Value that represent our state (<em>save</em>), and a way to build our State from that map (<em>restore</em>).</p><pre>companion object {<br>  val Saver: Saver&lt;LoginScreenComposableState, Any&gt; = run {<br>        mapSaver(<br>            save = { state -&gt;<br>                mapOf(<br>                    EmailKey to state.email,<br>                    PasswordKey to state.password,<br>                )<br>            },<br>            restore = { restoredMap -&gt;<br>                LoginScreenComposableState().apply {<br>                    email = restoredMap[EmailKey] as String<br>                    password = restoredMap[PasswordKey] as String<br>                }<br>            }<br>        )<br>    }<br><br>    private const val EmailKey: String = &quot;EmailKey&quot;<br>    private const val PasswordKey: String = &quot;PasswordKey&quot;<br>}</pre><p>The only thing missing is a way to instantiate this state from our composable.</p><pre>@Composable<br>fun rememberLoginScreenComposableState(): LoginScreenComposableState =<br>  rememberSaveable(saver = LoginScreenComposableState.Saver) {<br>      LoginScreenComposableState()<br>  }</pre><p>If we wrap-up everything we have this LoginScreenComposableState class 👇</p><pre>class LoginScreenComposableState {<br><br>    var email: String by mutableStateOf(&quot;&quot;)<br>        private set<br><br>    var password: String by mutableStateOf(&quot;&quot;)<br>        private set<br><br><br>    fun updateEmail(newValue: String) {<br>        email = newValue<br>    }<br><br>    fun updatePassword(newValue: String) {<br>        password = newValue<br>    }<br><br>    companion object {<br>        val Saver: Saver&lt;LoginScreenComposableState, Any&gt; = run {<br>            mapSaver(<br>                save = { state -&gt;<br>                    mapOf(<br>                        EmailKey to state.email,<br>                        PasswordKey to state.password,<br>                    )<br>                },<br>                restore = { restoredMap -&gt;<br>                    LoginScreenComposableState().apply {<br>                        email = restoredMap[EmailKey] as String<br>                        password = restoredMap[PasswordKey] as String<br>                    }<br>                }<br>            )<br>        }<br><br>        private const val EmailKey: String = &quot;EmailKey&quot;<br>        private const val PasswordKey: String = &quot;PasswordKey&quot;<br>    }<br><br>}<br><br>@Composable<br>fun rememberLoginScreenComposableState(): LoginScreenComposableState =<br>    rememberSaveable(saver = LoginScreenComposableState.Saver) {<br>        LoginScreenComposableState()<br>    }</pre><p>In our composable we can now instantiate our state :</p><pre>val composableState: LoginScreenComposableState = <br>    rememberLoginScreenComposableState()</pre><p>And use it in our texts fields :</p><pre>OutlinedTextField(<br>    value = composableState.email,<br>    onValueChange = composableState::updateEmail,<br>    placeholder = { Text(text = &quot;Email&quot;) },<br>    modifier = Modifier.fillMaxWidth()<br>)<br><br>OutlinedTextField(<br>    value = composableState.password,<br>    onValueChange = composableState::updatePassword,<br>    placeholder = { Text(text = &quot;Password&quot;) },<br>    modifier = Modifier.fillMaxWidth()<br>)</pre><h3>Add logic to our state</h3><p>Currently our state and our screen are quite simple, but, if we want a real login screen we need to add several things :</p><ul><li>A way to hide/show the password</li><li>A form validation that will enable or disable the “Login” button (if one of the field is empty)</li></ul><p>The “naive” way to do it will be to do it in our composable. But it will impact the code clarity.</p><p>So, in order to keep our compose code clean, we will add the logic directly in our state</p><pre>class LoginScreenComposableState {<br><br>    var email: String by mutableStateOf(&quot;&quot;)<br>        private set<br><br>    var password: String by mutableStateOf(&quot;&quot;)<br>        private set<br><br>    var hidePassword: Boolean by mutableStateOf(true) 👈 // New<br>        private set<br><br>    val passwordVisualTransformation: VisualTransformation 👈  // New<br>        get() = if (hidePassword) {<br>            PasswordVisualTransformation()<br>        } else {<br>            VisualTransformation.None<br>        }<br><br>    val passwordTrailingIcon: ImageVector 👈 // New<br>        get() = if (hidePassword) {<br>            Icons.Default.Visibility<br>        } else {<br>            Icons.Default.VisibilityOff<br>        }<br><br>    val isFormValid: Boolean 👈 // New <br>        get() = email.isNotEmpty() &amp;&amp; password.isNotEmpty()<br><br>    fun updateEmail(newValue: String) {<br>        email = newValue<br>    }<br><br>    fun updatePassword(newValue: String) {<br>        password = newValue<br>    }<br><br>    👇 // New<br>    fun togglePasswordVisibility() { <br>        hidePassword = !hidePassword<br>    }<br><br>    companion object {<br>        val Saver: Saver&lt;LoginScreenComposableState, Any&gt; = run {<br>            mapSaver(<br>                save = { state -&gt;<br>                    mapOf(<br>                        EmailKey to state.email,<br>                        PasswordKey to state.password,<br>                        HidePasswordKey to state.hidePassword 👈 // New<br>                    )<br>                },<br>                restore = { restoredMap -&gt;<br>                    LoginScreenComposableState().apply {<br>                        email = restoredMap[EmailKey] as String<br>                        password = restoredMap[PasswordKey] as String<br>                        hidePassword = restoredMap[HidePasswordKey] as Boolean 👈 // New<br>                    }<br>                }<br>            )<br>        }<br><br>        private const val EmailKey: String = &quot;EmailKey&quot;<br>        private const val PasswordKey: String = &quot;PasswordKey&quot;<br>        private const val HidePasswordKey: String = &quot;HildePasswordKey&quot; 👈 // New<br>    }<br><br>}</pre><p>We can now simply call the values from our state in our composable :</p><pre>OutlinedTextField(<br>    value = composableState.email,<br>    onValueChange = composableState::updateEmail,<br>    placeholder = { Text(text = &quot;Email&quot;) },<br>    modifier = Modifier.fillMaxWidth()<br>)<br><br>OutlinedTextField(<br>    value = composableState.password,<br>    onValueChange = composableState::updatePassword,<br>    placeholder = { Text(text = &quot;Password&quot;) },<br>    modifier = Modifier.fillMaxWidth(),<br>    visualTransformation = composableState.passwordVisualTransformation,<br>    trailingIcon = {<br>        IconButton(composableState::togglePasswordVisibility) {<br>            Icon(<br>                imageVector = composableState.passwordTrailingIcon,<br>                contentDescription = &quot;Change password visibility&quot;<br>            )<br>        }<br>    }<br>)</pre><p>We now have a great looking login screen 🥳👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*fKDLpgRW04VvKwXpQ1I9Xg.gif" /></figure><p><strong>Now you know how to use the state in order to create a form screen 🤩🎯</strong></p><p>Keep in mind that we’ve only describe a simple use case, but if you need to develop a more complex screen, this article can be a good entry point 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*d_5pHupY2vBeV7G1kUiZqA.png" /><figcaption><a href="http://www.linkedin.com/in/florian-ngbala">Florian N’Gbala</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3ca218a354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom Theme with Jetpack Compose]]></title>
            <link>https://lunabee-studio-dev.medium.com/create-a-custom-theme-with-jetpack-compose-3720fc18e01?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/3720fc18e01</guid>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 08:51:19 GMT</pubDate>
            <atom:updated>2023-03-21T08:17:26.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Doing Android apps is part of our daily job at <a href="https://www.lunabee.studio/">Lunabee Studio</a>. For almost 15 years the company strived to develop great apps using the best native technologies available.</p><p><strong>So when Google released Jetpack compose, a technology that has the potential to revolutionize the Android eco-system we knew we had to try.</strong></p><p>Switching to Compose was not an easy journey, we encountered many pitfalls along the way. But now that we just released our first full Compose app in production, looking back,<strong> the challenge was worth it</strong>.</p><p><em>The goal of this article is to show you a way to </em><strong><em>implement a custom theme</em></strong><em>, a step quite important when developing a new app 😉</em></p><h3>🏋️ Warm-up</h3><p>Our UI/UX team just finished the design of our example app : Hikes, an app displaying the best landscapes of the Alps 🏔️ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnhyF0fGJhKoTaWqD_5NOw.png" /></figure><p>Our theme will be composed of three main properties, the <strong>color</strong>, the <strong>typography</strong> and the <strong>shapes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*7XdVIpFJ89oOIPhCXVhaPg.png" /></figure><h3>🎨 The color scheme of our app</h3><p>Here is the color palette we are going to implement in our app. 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*taV0hFW7cd65NEic6puWnw.png" /></figure><p>For the sake of simplicity, we wanted to keep it small, but our implementation will also work with a much bigger palette.</p><p>Our first job will be to “<em>convert</em>” it into Kotlin. And as you can see in the code bellow, it’s quite straight forward:</p><pre>object HikesPalette {<br>    val White = Color(0XFFFFFFFF) <br>    val Green80 = Color(0xFF83F9BF)<br>    val Green40 = Color(0xFF006C47)<br>    val Green20 = Color(0xFF003823)<br>    val Gray99 = Color(0xFFFBFDF8)<br>    val Gray90 = Color(0xFFE1E3DF)<br>    val Gray10 = Color(0xFF191C1A)<br>}</pre><p>Now that the code of our palette has been written, we can <strong>implement the color scheme</strong>.</p><p>Nowadays a particular attention is set on the dark mode of an app. Thus, most of the apps we use have two schemes : <em>one for the light mode and one for the dark one</em>.</p><p><strong><em>More info on the topic:</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO_eOuvYlgw0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO_eOuvYlgw0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO_eOuvYlgw0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f07a707a71213e4f68eac13e281f2806/href">https://medium.com/media/f07a707a71213e4f68eac13e281f2806/href</a></iframe><p>Here are the two color schemes we are going to implement 👇</p><p>Let’s first create a “<em>contract</em>” (or an interface 😉) that the two color schemes must follow.</p><pre>interface HikesColorsScheme {<br>    val main: Color<br>    val mainContent: Color<br>    val background: Color<br>    val text: Color<br>}</pre><p>Now that it has been done, we can easily create the two color schemes using the palette above:</p><pre>// Light theme<br>object HikesLightColorsScheme : HikesColorsScheme {<br>    override val main: Color = HikesPalette.Green40<br>    override val mainContent: Color = HikesPalette.White<br>    override val background: Color = HikesPalette.Gray99<br>    override val text: Color = HikesPalette.Gray10<br>}<br><br>// Dark theme<br>object HikesDarkColorsScheme : HikesColorsScheme {<br>    override val main: Color = HikesPalette.Green80<br>    override val mainContent: Color = HikesPalette.Green20<br>    override val background: Color = HikesPalette.Gray10<br>    override val text: Color = HikesPalette.Gray90<br>}</pre><h3>🖊️ The Typography</h3><p>Now that the color has been dealt with, we are going to take a look at the typography of our app. Here are the six different types that we are going to use. To represent that in a “code” perspective, we will define an object having six variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*o3R9b87RDY_5nb0Lkkok_A.png" /></figure><pre>object HikeTypography {<br><br>  val header = TextStyle(<br>        fontFamily = Montserrat,<br>        fontSize = 42.sp,<br>        fontWeight = FontWeight.W900<br>    )<br><br>    val title = TextStyle(<br>        fontFamily = Montserrat,<br>        fontSize = 22.sp,<br>        fontWeight = FontWeight.W700<br>    )<br><br>    val action = TextStyle(<br>        fontFamily = Montserrat,<br>        fontSize = 16.sp,<br>        fontWeight = FontWeight.W600<br>    )<br>  <br>  val labelBold = TextStyle(<br>    fontFamily = Montserrat,<br>        fontSize = 16.sp,<br>        fontWeight = FontWeight.W600<br>    )<br><br>    val bodyBold = TextStyle(<br>        fontFamily = Montserrat,<br>        fontSize = 14.sp,<br>        fontWeight = FontWeight.W500<br>    )<br><br>    val body = TextStyle(<br>        fontFamily = Montserrat,<br>        fontSize = 14.sp,<br>        fontWeight = FontWeight.W400<br>    )<br>}</pre><h3>🟩 The Shapes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*Ljae2jzKYh_82ip_STBc8w.png" /></figure><p>Concerning the shapes, we are going to do the same as before. We have three different shapes in our app, so let’s write that in a Kotlin way.</p><pre>object HikeShape {<br>    val smallRoundedCornerShape: RoundedCornerShape<br>        @Composable<br>        get() = RoundedCornerShape(4.dp)<br><br>    val mediumRoundedCornerShape: RoundedCornerShape<br>        @Composable<br>        get() = RoundedCornerShape(8.dp)<br><br>    val largeRoundedCornerShape: RoundedCornerShape<br>        @Composable<br>        get() = RoundedCornerShape(12.dp)<br>}</pre><h3>🎁 Provide the theme’s attributes</h3><p>All our theme’s attributes have been defined. But one question remains: <strong><em>How will theses attributes be passed to our composables ?</em></strong></p><pre>object HikesTheme {<br>    val colors: HikesColorsScheme = ... ?<br>    val typography: HikeTypography = ...?<br>    val shapes: HikesShape = ...?<br>}</pre><p>Indeed, color, shape and typo are properties we need to access a lot of times in each of our composables (to define the background of a button, the border of a textfield etc…). Passing down the attributes to use to each composable seems a bit painful 🙄. Hopefully, there is a tool that will help us achieve our goal 👉 <a href="https://developer.android.com/jetpack/compose/compositionlocal"><strong>CompositionLocal</strong></a><strong>.</strong></p><p>CompositionLocal will help us pass data down to the composition implicitly. In other words, we will be able to do HikesTheme.colors.main in every components of our composition tree without bothering to know if the app needs to use the light or dark theme.</p><p>Let’s start by defining a “<strong>Provider</strong>” for each properties 👇</p><pre>val LocalHikesColor: ProvidableCompositionLocal&lt;HikesColorsScheme&gt; =<br> staticCompositionLocalOf { error(&quot;no provided&quot;) }<br><br>val LocalHikesTypography: ProvidableCompositionLocal&lt;HikeTypography&gt; = <br> staticCompositionLocalOf { error(&quot;no provided&quot;) }<br><br>val LocalHikesShape: ProvidableCompositionLocal&lt;HikesShape&gt; = <br> staticCompositionLocalOf { error(&quot;no provided&quot;) }</pre><p>We can now fill the missing code in our <strong>HikesTheme</strong>:</p><pre>object HikesTheme {<br>    val colors: HikesColorsScheme<br>        @Composable<br>        get() = LocalHikesColor.current<br><br>    val typography: HikeTypography<br>        @Composable<br>        get() = LocalHikesTypography.current<br><br>    val shapes: HikesShape<br>        @Composable<br>        get() = LocalHikesShape.current<br>}</pre><p>The next thing to do is to use <strong><em>CompositionLocalProvider</em></strong> in order to provide the attributes to the rest of the app.</p><pre>val localHikesColors: HikesColorsScheme = if (darkTheme) {<br>      HikesDarkColorsScheme<br>  } else {<br>      HikesLightColorsScheme<br>  }<br>  CompositionLocalProvider(<br>      LocalHikesColor provides localHikesColors,<br>      LocalHikesTypography provides HikeTypography,<br>      LocalHikesShape provides HikesShape<br>  ) {<br>      { .... The content of Our App ....}<br>  }<br>}</pre><p>We are now ready to create the screens of our beautiful app! Well, nearly ready 😁….</p><p>A lot of composables provided by Google use material theme to style themselves. For instance, a button will use by default the MaterialTheme.colorScheme.primary color for its background.</p><p>But with our current implementation <strong>we did not specify it</strong>, and thus all the buttons will have a default color (which is close to purple 😅), unless we explicitly tell them each time which color to use, which can be very painfull, and not very optimal.</p><p>To solve that, <strong>we will create a mapping from our color scheme to the MaterialTheme’s color scheme</strong>.</p><h3>🧪 Enrich Material Theme</h3><pre>fun mapMaterialColorScheme(<br>    darkTheme: Boolean,<br>    hikesColors: HikesColorsScheme<br>) = if (darkTheme) {<br>    darkColorScheme(<br>        primary = hikesColors.main,<br>        onPrimary = hikesColors.mainContent,<br>        background = hikesColors.background,<br>        onBackground = hikesColors.text<br>    )<br>} else {<br>    lightColorScheme(<br>        primary = hikesColors.main,<br>        onPrimary = hikesColors.mainContent,<br>        background = hikesColors.background,<br>        onBackground = hikesColors.text<br>    )<br>}</pre><p>The above function will map our color with some of the Material theme color. We did not map all the color but if you want to do it it’s possible 😉.</p><p>If you want to see all available colors with Material 3, check this👇</p><p><a href="https://m3.material.io/styles/color/the-color-system/tokens#374c255d-600d-4e73-9755-e75a5bb1134f">Color system - Material Design 3</a></p><p><strong>We are now ready to build our theme! 🎉</strong></p><h3>Let’s build our theme</h3><p>We just need to fill the “…” in the snipet above with: 👇</p><pre>MaterialTheme(<br>    colorScheme = mapMaterialColorScheme(darkTheme, localHikesColors)<br>) {<br>   content()<br>}</pre><p>And thus we have :</p><pre>@Composable<br>fun HikesTheme(<br>    darkTheme: Boolean = isSystemInDarkTheme(),<br>    content: @Composable () -&gt; Unit<br>) {<br><br>    val localHikesColors: HikesColorsScheme = if (darkTheme) {<br>        HikesDarkColorsScheme<br>    } else {<br>        HikesLightColorsScheme<br>    }<br><br>    CompositionLocalProvider(<br>        LocalHikesColor provides localHikesColors,<br>        LocalHikesTypography provides HikeTypography,<br>        LocalHikesShape provides HikesShape<br>    ) {<br>       MaterialTheme(<br>            colorScheme = mapMaterialColorScheme(darkTheme, localHikesColors)<br>       ) {<br>            content()<br>        }<br>    }<br>}</pre><p>We can now complete the code of the MainActivity :</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>          HikesTheme {<br>              Surface() {<br>                Column(<br>                    modifier = Modifier<br>                        .fillMaxSize()<br>                        .padding(24.dp),<br>                    verticalArrangement = Arrangement.spacedBy(16.dp)<br>                ) {<br>                    Text(<br>                        text = &quot;Header&quot;,<br>                        style = HikesTheme.typography.header<br>                    )<br>                    Text(<br>                        text = &quot;Title&quot;,<br>                        style = HikesTheme.typography.title<br>                    )<br>                    Text(<br>                        text = &quot;Action&quot;,<br>                        style = HikesTheme.typography.action<br>                    )<br>                    Text(<br>                        text = &quot;Body bold&quot;,<br>                        style = HikesTheme.typography.bodyBold<br>                    )<br>                    Text(<br>                        text = &quot;Body Regular&quot;,<br>                        style = HikesTheme.typography.body<br>                    )<br><br>                 <br>                    Box(<br>                        modifier = Modifier<br>                            .size(50.dp)<br>                            .clip(HikesTheme.shapes.smallRoundedCornerShape)<br>                            .background(HikesTheme.colors.main)<br>                    )<br><br>                    Box(<br>                        modifier = Modifier<br>                            .size(50.dp)<br>                            .clip(HikesTheme.shapes.mediumRoundedCornerShape)<br>                            .background(HikesTheme.colors.main)<br>                    )<br><br>                    Box(<br>                        modifier = Modifier<br>                            .size(50.dp)<br>                            .clip(HikesTheme.shapes.largeRoundedCornerShape)<br>                            .background(HikesTheme.colors.main)<br>                    )<br>                  }<br>              }<br>          }<br>      }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*DdY0wN0qr3TYs5Lgso7bxA.png" /></figure><p><strong>And that’s it, well done</strong>!👏. We’ve just created a truly custom theme for an app using <strong>Jetpack Compose</strong>. It’s is a rather simple process but we need to do it well if we want great-looking apps 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*d_5pHupY2vBeV7G1kUiZqA.png" /><figcaption><a href="http://www.linkedin.com/in/florian-ngbala">Florian N’Gbala</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3720fc18e01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widget iOS 14 — Xcode 12 generated widget code overview]]></title>
            <link>https://lunabee-studio-dev.medium.com/widget-ios-14-xcode-12-generated-widget-code-overview-6db544b2f141?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db544b2f141</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[widgetkit]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[ios-14]]></category>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Thu, 15 Oct 2020 14:34:37 GMT</pubDate>
            <atom:updated>2020-10-15T14:48:36.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS 14 Widget — Xcode 12 generated widget code overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UxQi_1I45IjIgUWu" /><figcaption>Photo by <a href="https://unsplash.com/@thombradley?utm_source=medium&amp;utm_medium=referral">Thom Bradley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Summary</h3><ul><li><a href="https://medium.com/@lunabeestudiodev/widgets-ios-14-possibilities-design-good-practices-and-limitations-d40e566715af">Possibilities, design good practices and limitations</a></li><li><strong>Xcode 12 generated widget code overview</strong></li><li>Create a basic widget — <em>Coming soon</em></li><li>Create an advanced widget — <em>Coming soon</em></li></ul><h3>Introduction</h3><p>Creating a widget is <strong>not complex but can quickly take time</strong>. While a very simple widget can be done very fast, a real, well-made case will take more time to deal with all of the scenarios and ensure that the widget is always in good state with the application. You should know that widgets are necessarily created in <strong>SwiftUI</strong>, but don’t panic, even applications using <strong>UIKit can benefit from it</strong>.</p><h3>Widget creation with Xcode 12</h3><p>File &gt; New &gt; Target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_2TbMZ0mNVSnxg1nooBaQ.png" /><figcaption>Create the widget target from Xcode 12</figcaption></figure><p>Then choose Widget extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOHNHQhZLjfZ8f-hlW9wbw.png" /><figcaption>Choose Widget Extension in Xcode 12</figcaption></figure><p>Finally, you must indicate the name of the target as well as the application for which you want to create this target (in the case where you have a dev app and a prod app for example).</p><p>Particular point on this last step of creating the widget target: you have to choose whether you want to include “<strong>Configuration Intent</strong>”. If we check this option, we’ll be able to add <strong>options directly from the widget</strong> (without opening the application), while if we do not check it, our configuration will be static (no option directly from the widget).</p><p>To put it simply, we are going to start creating our widget without checking this option, but we will come back to it later (in a future article).</p><h3>Generated code by Xcode 12</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*Z0CWZEPVwa5JznDdGw3ajg.png" /><figcaption>Generated code by Xcode when we create a new iOS 14 Widget target</figcaption></figure><p>When creating a widget, Xcode only <strong>generates 3 things</strong> for us:</p><ul><li>the <strong>Assets folder</strong> (for managing images, colors, etc)</li><li>the <strong>Info.plist</strong> file (for the global configuration of the widget)</li><li>the <strong>widget code</strong> (the most interesting part)</li></ul><p>By opening the main widget file, we can see that it contains quite a few things:</p><h4>Main definition of the widget</h4><p>This struct allows to <strong>define the widget as such</strong>. With this definition that we can choose whether we want a <strong>static or dynamic widget</strong> (the intents as we saw earlier). It also allows us to <strong>define the provider</strong> that you’ll use to provide the data to the widget and the view that you want to use. And finally, it’s also this definition that allows us to <strong>choose the name</strong> you want to give to the widget <strong>as well as its description</strong> (visible in the iOS widget library).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*O1_v3Nr0ky_-BOcmRxzmRg.png" /><figcaption>Widget main definition</figcaption></figure><h4>The provider</h4><p>The provider is divided into three parts: the placeholder, the snapshot and the timeline.</p><p>The <strong>placeholder</strong> allows us to define the view that we want to <strong>display during the loading</strong> of the widget with the real information. In reality, this view will be <strong>used in “skeleton” mode</strong> by iOS. Usually, we’ll use the same view we use for our widget with the only difference being that we’ll use fake data to make the loading of the placeholder <strong>as fast as possible</strong>.</p><p>The <strong>snapshot</strong> allows us to define the <strong>view we want to display in the iOS widgets library</strong>. Unlike the placeholder, here we can take a little longer to fetch <strong>real information</strong> to display to the user. It’s even recommended: it will <strong>show the user that the widget is responding well to the current state</strong> of their application.</p><p>The <strong>timeline</strong> will be used to <strong>prepare the different entries to display over time</strong> in our widget: we define <strong>several dates</strong> on which we ask the widget to update to display the new information.</p><p>In the code that was generated by Xcode, we can see that we generate 5 entries one hour apart from the current time. Then we choose a Timeline with the policy atEnd, which will have the effect of refreshing the widget every hour to display these different entries. Actually, there are <strong>several strategies for refreshing the widget</strong>, but we will come back to that later (in the next article).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*jUrgER9NacHsZiLZpU7ZZA.png" /><figcaption>Widget provider</figcaption></figure><h4>The model</h4><p>The template that will be used to <strong>display the data</strong> in the widget.</p><p>This structure must necessarily inherit from TimelineEntry so that it can be used with our widget. In fact, it forces us to have a date (used for our widget’s refresh strategy). Obviously, i<strong>f your model becomes too complicated, do not hesitate to divide it into several substructures</strong>.</p><p>In this case, since the purpose of the widget generated by Xcode is to display times, the date is more than enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*C4UTl3wCyC2TGdpq9hCuGg.png" /><figcaption>Widget model</figcaption></figure><h4>The view and it’s preview</h4><p>Since the widgets are created in SwiftUI only, we end up with a classic SwiftUI view. This view takes an entry (which corresponds to our model) as a parameter, and then displays the information we want to see in our widget.</p><p>The preview use the SwiftUI view with a fake entry, which allows us to use the SwiftUI previews to ensure that the widget is correctly rendered in different states (light and dark mode, at a certain date, etc).</p><p>The only small thing to be careful of here: the preview <strong>must specify a </strong><strong>previewContext</strong>, otherwise Xcode will refuse to display the preview. This is not bad because it allows us to choose whether we want to see the rendering for an S, M or L widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*gvVDxKb5FFiN9cmgHFwQ2Q.png" /><figcaption>Widget view and preview</figcaption></figure><h4>Xcode widget generated code result</h4><p>Unsurprisingly after seeing the code, we end up with something very simple that displays the time centered vertically and horizontally in our widget (for S, M and L sizes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*SfAoK6V-UX4t0tEofYI8wg.png" /><figcaption>Xcode widget generated code result (M and L sizes)</figcaption></figure><h3>What’s next?</h3><p>If you missed the previous article, you can read it here: <a href="https://medium.com/@lunabeestudiodev/widgets-ios-14-possibilities-design-good-practices-and-limitations-d40e566715af">Possibilities, design good practices and limitations</a>.</p><p>Then, you can see <strong>Create a basic widget</strong> (<em>Coming soon)</em> or <strong>Create an advanced widget</strong>(<em>Coming soon) </em>if you want to learn more about Widgets and how to create them.</p><p>And don’t forget to “clap” and share this article if you like it and want to see more content like this! 👏</p><p>Thanks for reading,</p><p>Authors: Alexandre Cools</p><p><a href="http://www.lunabee.studio/"><strong>Lunabee Studio</strong></a><strong> is a company creating premium mobile Apps in the Alps. We love mobile UX, iOS and Android. </strong><a href="https://twitter.com/lunabeeStudio"><strong>Follow us</strong></a><strong> to keep up with our latest publications and news.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db544b2f141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widgets iOS 14 - Possibilities, design good practices and limitations]]></title>
            <link>https://lunabee-studio-dev.medium.com/widgets-ios-14-possibilities-design-good-practices-and-limitations-d40e566715af?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40e566715af</guid>
            <category><![CDATA[good-practices]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[widgetkit]]></category>
            <category><![CDATA[limitations]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 09:32:10 GMT</pubDate>
            <atom:updated>2020-10-15T15:13:53.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS 14 Widgets- Possibilities, design good practices and limitations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CumBWXy_EuAeSyYW" /><figcaption>Photo by <a href="https://unsplash.com/@omidarmin?utm_source=medium&amp;utm_medium=referral">Omid Armin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since iOS 14, widgets finally allow users to customize (a little) their iPhone Home screens.</p><p>Through this series of articles focused on widgets, we’ll present to you all the possibilities they provide as well as the best practices or limitations that they impose to us.</p><h4><strong>Summary</strong></h4><ul><li><strong>Possibilities, design good practices and limitations</strong></li><li><a href="https://lunabee-studio-dev.medium.com/widget-ios-14-xcode-12-generated-widget-code-overview-6db544b2f141">Xcode 12 generated widget code overview</a></li><li>Create a basic widget — <em>Coming soon</em></li><li>Create an advanced widget — <em>Coming soon</em></li></ul><h3><strong>What are widgets for?</strong></h3><p><strong>It’s important to understand what purpose do widgets serve.</strong></p><p>In a general manner, widgets are meant to give the user a snippet of information from your app (partially because of their rather small size, they can only contain so many things). It’s a bit of personally relevant content that allows them not to open the app.</p><p>For example, the weather app’s widget usually displays today’s weather only, in the location selected within the app. By showing this small bit of information, the users don’t have to open the app to find out what the weather is: in one glance, they know if they should take an umbrella or not.</p><p>That’s what a widget should do: <strong>display a bit of useful content that can be absorbed easily, in a glance.</strong></p><p>With iOS, widgets come in 3 sizes: small (taking up the space of 2x2 app icons), medium (2x4 app icons) and large (4x4app icons). For the first time, they can live within the user’s home screen. This allows another level of customization for the users, allowing them to choose what piece of information they want to see on the get-go. Even better, with Smart stacks and Siri suggestions, the widgets displayed can vary depending on the moment of the day, just so that the users get the right information at the right moment. Early morning ? Let’s show you the weather. Work time ? Maybe your calendar and appointments could be useful to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4D5DhkRBwWH23ofiaiw6A.png" /><figcaption>Different size of widgets</figcaption></figure><h3><strong>How does it work?</strong></h3><p>The whole mechanism of widgets is <strong>based on time management</strong> (and sometimes the goodwill of the system).</p><p>The developers define several states as well as the next display steps and give them dates (dates when the system should refresh the widget to display new informations). As it is not always possible to predict when the widget should refresh, it is also possible to force the refresh of it directly from the app.</p><p>Ultimately, <strong>a widget is just one (or more) pieces of information to display on a certain date for a certain period of time</strong>. It will adapt its display according to the data it receives from the application assigned to it.</p><h3><strong>Widgets design good practices</strong></h3><h4><strong>Content</strong></h4><ul><li><strong>Choosing and sticking to one idea: </strong>As stated earlier, widgets shouldn’t display too many information at once. First, because of their limited size. Second, because it should display information that can be digested quickly. Third, because it is meant to highlight a key feature of your app. With this in mind, <strong>sticking to one idea</strong> will help you create a widget that gives meaningful content to the user.</li><li><strong>Dynamic content: </strong>Widgets show information relevant to the users. They’ll be more likely to use it and place it on their home screen if it the content shown changes depending on the time of the day, or current events… It keeps the information interesting and delightful. Be one step ahead of the users, and give them the right information at the right moment.</li><li><strong>Only use different sizes if it brings value: </strong>You don’t have to make your widget available in every size. Take in consideration the degree of focus every size offers: the small widget has a greater content focus than the large widget. Maybe your concept works best with two small widgets, or maybe a medium and a large one are better.</li><li><strong>Pay attention to your micro-copy: </strong>Again, since you can only display so much, your micro-copy should be well written and thought. In very few words, you have to convey a clear message around your concept. If there’s an error, they have to understand what to do immediately, etc.</li></ul><h4><strong>Visual identity and design</strong></h4><p>This one can be tricky as multiple parameters come to play.</p><ul><li><strong>Fonts: </strong>If your identity uses particular fonts, consider using Apple SF fonts for your widget. As it will be placed on the users home screens, it will visually fit best if it uses the same font as the rest of the interface. With that said, custom fonts are ok, but have to be used sparingly.</li><li><strong>Colors: </strong>Colors are okay to use! Just take in consideration the fact that bold colors can take the attention away from the message you’re trying to convey. Try to use them as clues of your identity, or to drag the eyes of the users to the data you’re showing them.</li><li><strong>Identity: </strong>As the name of your app will be displayed below your widget, you don’t have to include it within the design. Instead, use color clues or a small version of your logo.</li></ul><p>On a broader spectrum…</p><ul><li><strong>Make sure it’s legible: </strong>This goes along with everything that has been said already, but when designing your widget, you have to find balance with content. It should show enough content so that it doesn’t look visually empty or useless, but not so much content that it looks too busy and isn’t easily readable. Again, users should understand the information given to them in a glance. <strong>Margins</strong> play a huge role in this: Apple suggests using standard 16 pt margins, allowing tight 8 px margins to help make graphics that contain a lot of information easier for people to read.</li><li><strong>Font sizes: </strong>Consider using sizes included between 12 pt and 15 pt. If displaying data or highlighting a very short amount of characters, you can up the size to about 30 pt.</li><li><strong>Dark Mode: </strong>Consider supporting dark mode, whether or not your app supports it. This will avoid any kind of friction with your user.</li></ul><h4><strong><em>Usage</em></strong></h4><ul><li><strong>Deep-linking and tap targets: </strong>Your widget can and should link to parts of your apps (it shouldn’t simply serve the purpose of launching your app). A small widget can display only one tap target, but medium and large widgets can display more. Although you could fill the surface with different tap targets, avoid offering too many, so that the users can tap the one they want with no trouble.</li><li><strong>Friction points: </strong>List every pain point that your user could encounter while using your widget: loss of connection, need of authentication, no content to display… and prepare your design, your copy accordingly, just so that the user knows what is happening and what to do. This includes designing a placeholder for your widget, for example.</li></ul><h3><strong>What are widgets limitations?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*UU3LWglrR-yenXOFzsGQdQ.gif" /></figure><p>Widgets are very useful for quickly showing information to the user and adding some quick actions to that information, but they also have their limitations:</p><ul><li>A widget is first of all <strong>linked to an application</strong>; it is not possible to create a widget without a parent application.</li><li>Each touch on the widget will <strong>necessarily open the application</strong>, no matter what. However, it is possible to redirect the user in the application via deeplinks.</li><li>The widget <strong>cannot ask for authorization</strong> from the user (like bluetooth for example). In this kind of case, it will be up to the application to manage all the associated mechanism and to request the widget refresh.</li><li>The size of a widget cannot be changed; it is <strong>not possible to scroll inside them</strong> for example.</li></ul><p>Keep in mind that widgets are made primarily for displaying data, nothing more.</p><h3><strong>Conclusion</strong></h3><p>In very few words: <strong>Keep it simple.</strong></p><p>A widget is a mean to highlight key content of your app without having to actually open the app. It should display clear information that can be digested in a glance and details that can be read with a longer look. Design wise, it means a somewhat minimalist design to push your content forward without creating too much noise on the screen. It means crafting a meaningful experience for your users, allowing them to customize their device further with your app and what it has to offer.</p><h3>🎁 Bonus</h3><p>Here you can find a Sketch file with some useful templates for iOS 14 widget. <br>Feel free to share it!</p><p><a href="https://github.com/LunabeeStudio/TechResources/tree/master/WidgetKit/Article-1">iOS 14 Widgets templates</a></p><h3>What’s next?</h3><p>See <a href="https://lunabee-studio-dev.medium.com/widget-ios-14-xcode-12-generated-widget-code-overview-6db544b2f141"><strong>Xcode 12 generated widget code overview</strong></a>, <strong>Create a basic widget</strong> (<em>Coming soon)</em> or <strong>Create an advanced widget</strong> (<em>Coming soon) </em>if you want to learn more about Widgets.</p><p>And don’t forget to “clap” this article if you like it and want to see more content like this! 👏</p><p>Thanks for reading,</p><p>Authors: Charlotte Jacquot (UI/UX) &amp; Alexandre Cools (iOS Developer)</p><p><a href="http://www.lunabee.studio/"><strong>Lunabee Studio</strong></a><strong> is a company creating premium mobile Apps in the Alps. We love mobile UX, iOS and Android. </strong><a href="https://twitter.com/lunabeeStudio"><strong>Follow us</strong></a><strong> to keep up with our latest publications and news.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40e566715af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realm Migration — Renaming a class and migrating nested objects]]></title>
            <link>https://lunabee-studio-dev.medium.com/realm-migration-renaming-a-class-and-migrating-nested-objects-e7a522af3713?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a522af3713</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[realm]]></category>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 13:13:10 GMT</pubDate>
            <atom:updated>2020-09-14T13:13:10.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Realm Migration — Renaming a class and migrating nested objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qtUSnpn5IYrFF1F2" /><figcaption>Photo by <a href="https://unsplash.com/@miless?utm_source=medium&amp;utm_medium=referral">Miles Storey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>A few days ago, I opened an old project to update its architecture.<br>I intended to rename my Realm classes and also update some class’ attributes (for example, instead of storing a list of objects in a Realm object, I only wanted to store the object ID in the child object).</p><p>Usually, to rename a class the only thing we have to do is “Cmd + Maj + A”, and then “Rename”, but in the case of Realm, it’s a little bit more complex as we have to do a migration to avoid user datas losts.</p><p>For this article, I’ll take this example:<br>we have two classes (User and Sport) and here is the Realm objects structure before the migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e661f603e1e8880a29e76dd2b65645/href">https://medium.com/media/93e661f603e1e8880a29e76dd2b65645/href</a></iframe><p>Every sport has an ID, a name and a list of User, and every user has an ID, a first name, a last name and a Sport object.</p><p>Here is the Realm objects structure that I want at the end of the migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89478f7be815ee22344e1fee0061ad14/href">https://medium.com/media/89478f7be815ee22344e1fee0061ad14/href</a></iframe><p>So, instead of storing a Sport object for a user, I intend to save only the ID of the sport. And for the Sport object, I don’t want to save the list of users anymore.</p><p>Also, I wanted to rename both classes and prefix them by R (R for Realm), because I intend to reuse the old classes name in my current code, for my UI objects.</p><p>Before starting the migration, I created the new classes (R classes) in my project and I removed the old ones (then, I also updated the application to be able to compile my project).</p><p>Let’s start the migration now!</p><p>To complete the migration and reach my goals, there are two steps:</p><ul><li>Rename both Realm classes in the database</li><li>Don’t forget to migrate the user’s data!</li></ul><h3>Renaming a class</h3><p>When I’m doing a class migration, I can create the new object (RSport for the Sport object for example), and then, I can remove the old object.</p><p>So, the truth is that we are not renaming a class, but we are creating a new class from the new object. Then, we migrate the user’s data and at the end, we remove the old object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/111ae3ee66c949f54efb9d62d46b4799/href">https://medium.com/media/111ae3ee66c949f54efb9d62d46b4799/href</a></iframe><p>I’m going to explain the different steps:</p><ul><li>Lines 2 to 4: We recover the old object information (in this case, the ID and the sport’s name)</li><li>Line 6: We ask the migration object to create the new R object (RSport)</li><li>Lines 7 and 8: We associate the old object’s values to the new object to keep all user’s information</li><li>Line 10: We remove the old object (Sport), as we don’t need it anymore</li></ul><p>We’ve done the “renaming” of the first Realm object (Sport to RSport).</p><p>Now, let’s get the migration started, with a more complex object (this object contains another Realm object in it, so it’s a little bit different)</p><h3>Migrate a complex Realm object included in another Realm object</h3><p>Like the Sport object, we’re gonna start to create the new object (renaming the class), before starting to migrate all the attributes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5531701915722a9960b62fc75b3d4e1d/href">https://medium.com/media/5531701915722a9960b62fc75b3d4e1d/href</a></iframe><p>Again, like the Sport object, we loop on all old objects of the database, we get all the datas, we create new objects, we copy the data and then, we remove the old object as we don’t need it anymore.</p><p>Well done, but if we stop here, we loose the user’s sport…</p><p>The problem: how to get the id of the Sport object inside the User object that we want to migrate?</p><p>If we try to do it like all others attributes, we do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa01ebefe88edf11f719bc9621505736/href">https://medium.com/media/fa01ebefe88edf11f719bc9621505736/href</a></iframe><p>We get an object of type Any:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*asiPO9jlFnUeVq7xkkK86A.png" /><figcaption>Sport object data from the User object</figcaption></figure><p>We can’t cast the object to the Sport type, as this class doesn’t exist anymore (remember, we deleted it before starting the migration process). Also, we can’t cast it to RSport type, because this class is not equivalent to the Sport type.</p><p>(But we can still see all information; that’s a good start!)</p><p>The only type in which we can still cast the object, it’s a type that the application still has. As we are working with Realm, and that all Realm objects inherit from the object “Object”, we can cast our object to the “Object” type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a07990336e6dca7a8617e8c5145a2ea6/href">https://medium.com/media/a07990336e6dca7a8617e8c5145a2ea6/href</a></iframe><p>We haven’t made progress here, as we didn’t have access to the ID of the Sport object yet.</p><p>If we try to do like the previous attribute, the compilator returns an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpDsz15QLIAfA1hXl14o7g.png" /><figcaption>Compilation error when we try to access to the Sport ID of the user like a key value dictionary</figcaption></figure><p>The solution:</p><p>Use the value(forKey:) function, that allows us to get the ID value of the old Sport object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41096afb2c14167ff7e3862347072207/href">https://medium.com/media/41096afb2c14167ff7e3862347072207/href</a></iframe><p>So, we finally have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e633e146ec6c7b31f5abdf49479d3189/href">https://medium.com/media/e633e146ec6c7b31f5abdf49479d3189/href</a></iframe><p>Like this, you can access an object contained inside another object when you do a Realm migration. By the way, here, it was a simple example, but you can also apply this solution to object inside object inside object, etc.</p><h3>What’s next?</h3><p>If you have any other solution to handle this kind of case, or if you have questions/comments, feel free to comment this post, I’ll answer you with great pleasure!</p><p>Thanks for reading,</p><p>Happy coding!</p><p>Author: Alexandre Cools<br><a href="https://twitter.com/Alexandre_Cools">https://twitter.com/Alexandre_Cools</a></p><p><a href="http://www.lunabee.studio/"><strong>Lunabee Studio</strong></a><strong> is a company creating premium mobile Apps in the Alps. We love mobile UX, iOS and Android. </strong><a href="https://twitter.com/lunabeeStudio"><strong>Follow us</strong></a><strong> to keep up with our latest publications and news.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a522af3713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make the most out of Pull Requests]]></title>
            <link>https://lunabee-studio-dev.medium.com/make-the-most-out-of-pull-requests-2b5fe8d5b88?source=rss-38f574390867------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5fe8d5b88</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[pr]]></category>
            <dc:creator><![CDATA[Lunabee Studio Dev]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 10:20:04 GMT</pubDate>
            <atom:updated>2020-02-03T10:24:27.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h31uQMHpsT7_6ZOeEehAwQ.png" /><figcaption>© Atlassian</figcaption></figure><p>The pull-request is a powerful tool that helps you keep code maintainability and quality. It’s mandatory in open source projects and should also be in private projects. Only two developers are needed to ensure that the project is well-taken care after, and maximize the chances of delivering bug-free releases. Be careful as it can be a double-edged sword taking time and instilling frustration if not done wisely.</p><h3>How to make a good Pull Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbBdsia9yM5XLayaJ8aICw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Pond</a> on <a href="https://unsplash.com/@jamesponddotco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><ul><li>A pull-request should always be made to fix one bug, refactor one part, add one new feature, etc… But only one! If you address multiple cases, please do multiple pull requests. The smaller the changes are, the easier they are to review and the fewer errors can slip into your project.</li><li>Test your changes thoroughly, every edge case must be handled. You must also think of how your changes might bring regression to other parts of the project. The reviewer is not your Quality Assurance. Even the Quality Assurance tester is not supposed to find your bugs. You should be accountable for the code you deliver and engage your reputation.</li><li>Read your own changes, it’s like checking your spelling when sending an email. After spending time making the changes, you may have forgotten that you wanted to refactor a part of it or left some unwanted commented code.</li><li>If anything is left undone, it should be stated in the description and a ticket must be created in your project management system.</li><li>When creating the pull request, try to explain in detail why and what it is for. If it makes sense, add screenshots or screen-recording to illustrate the purpose. Finally, indicate how to test the pull request by providing accounts with username and password or step by step guide to reproduce the bug or use the new feature.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i6-OlA-5SodE5Vskz85sA.png" /><figcaption>The template from <a href="https://github.com/android/plaid">Plaid</a> can be a nice skeleton to start with</figcaption></figure><h3>Benefits of a Pull Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbcX1_i38fH0i5unAOjhHA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Pond</a> on <a href="https://unsplash.com/@jamesponddotco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><ul><li><em>Errare humanum est</em>. Two <em>Errare humanum est</em> are possible but less probable: having your code read and tested by someone else reduce significantly the risk of having your project malfunctioning. It also helps to share the sense of ownership</li><li>Share of knowledge: As the saying says, sharing is caring. Either the reviewer is more experienced and his feedback should help the reviewed to improve, or the reviewer can learn from the code written by the expert.</li><li>Help make sure that at least two persons in the team are aware of the code. This way, if one is unavailable the other can answer the questions.</li></ul><h3>The dark side of a Pull Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVFAUj81-4naU-6ZFRmugw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Cheung</a> on <a href="https://unsplash.com/s/photos/star-wars-figurine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There is no denying that it’s time-consuming. Especially for new team members or if the code is not well written or well tested.</p><p>For the first, it’s a necessary thing to help them acquire the best practice used by the team or for the team to learn from the new inputs.</p><p>For the latter, you don’t want to ship code that doesn’t fit your standard so it prevents bad code from being merged on Master and your project to be full of bug.</p><h3>What a Pull Request is not</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*td1HOcJHH4_y-tGQwvs4Tw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Cheung</a> on <a href="https://unsplash.com/s/photos/star-wars-figurine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><ul><li>A way to have your code tested: Finding out that the code you asked to be reviewed is not doing what it’s supposed to will leave a really bad impression on the reviewer. It will be hard for him to trust you in the future.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*LIlrL3B_MVPFMxu7GyRaXw.png" /><figcaption>Actually, only +2 -1 with the same coding style config</figcaption></figure><ul><li>A code style checker: The formatting of the code should be shared beforehand and use by all the team to avoid having the real change bring by the pull request hidden in reformatting of the file.</li><li>A way to enforce your solution preferences: Nobody has the same way of writing code. Requesting changes should only be done to improve the project. If the solution is working well, deal with it.</li></ul><h3>TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBjU0tUiMx0d-c1Fb5XtEw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@arturtumasjan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artur Tumasjan</a> on <a href="https://unsplash.com/s/photos/star-wars-figurine?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><ul><li>The one making the pull request should do everything possible to make the life of the reviewer easier. When writing complicated code don’t hesitate to comment on it and make sure that you test what you deliver.</li><li>The one reviewing it shouldn’t judge the code. Make small, constructive and benevolent comments that will help the project. The goal is not to criticize the coder but elevate the project to higher ground.</li></ul><p>In the end, what’s most important is that the project benefits from the process and don’t you forget that you will be on both sides of a pull request. And as Justin Timberlake so rightly said :</p><blockquote>What goes around comes all the way back around</blockquote><p>___</p><p>Author: Quentin Metzler (aka Q2). <br><a href="https://twitter.com/Q2Android">https://twitter.com/Q2Android</a></p><p><a href="http://www.lunabee.studio/"><strong>Lunabee Studio</strong></a><strong> is a company creating premium mobile Apps in the Alps. We love mobile UX, iOS and Android. </strong><a href="https://twitter.com/lunabeeStudio"><strong>Follow us</strong></a><strong> to keep up with our latest publications and news.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5fe8d5b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>