<?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 Andrew Grosner on Medium]]></title>
        <description><![CDATA[Stories by Andrew Grosner on Medium]]></description>
        <link>https://medium.com/@abgrosner?source=rss-6d9ac5be3d46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6HFzP0V_8PxrSSNsE1Ydqg.jpeg</url>
            <title>Stories by Andrew Grosner on Medium</title>
            <link>https://medium.com/@abgrosner?source=rss-6d9ac5be3d46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:58:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abgrosner/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[React Hooks — Gotchas]]></title>
            <link>https://medium.com/fuzz/react-hooks-gotchas-b8fcd25cc1b6?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8fcd25cc1b6</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 13:57:36 GMT</pubDate>
            <atom:updated>2020-03-16T13:57:36.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Hooks — Gotchas</h3><p>React Hooks are a way to use features that typically were only available to class components in functional components. It adds the ability to useState , useContext , and many other features not only without the need to create class components — but also to reuse common behavior in a functional way. You can also write your own custom hooks, introducing an emphasis on reusability and conciseness.</p><p>If you are not familiar with how to use hooks, please read this <a href="https://reactjs.org/docs/hooks-intro.html">page</a>.</p><p>Though with amazing power, if not careful, you could end up causing trouble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eLIIGIQD2J5d08vwpk0pcA.png" /></figure><p>Hooks provide several benefits to a functional component — less code, functional programming, reusability. If not careful, they do also introduce a few gotchas you must look out for.</p><h3>Breakdown</h3><p>In this article we will touch upon four topics:</p><p><strong>Follow the Rules of Hooks</strong></p><p><strong>Hook Dependencies</strong></p><p><strong>useRef vs useState</strong></p><p><strong>State Objects with useState</strong></p><h3>Follow the Rules of Hooks</h3><p>As the <a href="https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions">Rules Of Hooks</a> states: <strong>Don’t call Hooks inside loops, conditions, or nested functions.</strong></p><p>What this means is that they <em>must</em> be top-level. A couple of illegal examples:</p><pre>const list = [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]<br>list.forEach((item: string) =&gt; {<br>  const [itemState, setItemState] = useState(item) // ERROR<br>})</pre><pre>if (condition) {<br> const [checked, setChecked] = useState(true)<br> // error<br> return &lt;span&gt;{checkedHook ? &#39;Checked&#39; : &#39;Not Checked&#39;}&lt;/span&gt; <br>} else {<br> return &lt;span&gt;Hello&lt;/span&gt;<br>}</pre><h3>Hook Dependencies</h3><p>Hooks may depend on props. These are called <em>hook dependencies.</em> Whenever a dependency changes, the hook is recalculated automatically. How does this work?</p><p>Let’s first look at an example of hooks that have dependencies. Currently in React we have: useEffect , useCallback , `useMemo`, `useLayoutEffect`, `useImperativeHandle`.</p><p>I’m guaranteeing you’ve used useEffectto dispatch an action on first load that calls an API. For example, you want to load a set of users:</p><pre>const MyComponent = () =&gt; {<br>  const dispatch  = useDispatch()<br>  useEffect(() =&gt; {<br>    dispatch(loadUsers())<br>  }, [dispatch])<br>  return &lt;span&gt;hello&lt;/span&gt;<br>}</pre><p>Which is all fine and dandy. What if you need to, for some reason, notify the parent component when that effect dispatches? You might expose a prop:</p><pre>const MyComponent = ({ startLoadingUsers }: Props) =&gt; {<br>  const dispatch  = useDispatch()<br>  useEffect(() =&gt; {<br>    dispatch(loadUsers())<br>    startLoadingUsers()<br>  }, [dispatch, startLoadingUsers])  <br>  console.log(&#39;RENDER CHILD&#39;) // let&#39;s log our renders<br>  return &lt;span&gt;hello&lt;/span&gt;<br>}</pre><p>Everything looks great. You expose it to the parent component as follows:</p><pre>const ParentComponent = () =&gt; {<br>  const [isLoading, setLoading] = useState(false)<br>  const users = useSelector(selectUsers)<br>  const loadUsers = () =&gt; {<br>    setLoading(true)<br>  }<br>  console.log(&#39;RENDER PARENT&#39;)</pre><pre>  return &lt;MyComponent startLoadingUsers={loadUsers} /&gt;<br>}</pre><p>What you might <strong>not</strong> expect is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OgIR3pTI-U16Hur1x47Ww.png" /></figure><p>The log goes infinitely and eventually will crash chrome when it runs out of memory.</p><p>What is happening? Let’s break it down:</p><ol><li>In our child component:</li></ol><pre>useEffect(() =&gt; {<br>    dispatch(loadUsers())<br>    startLoadingUsers()<br>  }, [dispatch, startLoadingUsers])</pre><p>We’re passing a function reference for startLoadingUsers . If that reference changes, we recompute the effect here.</p><p>2. Our parent component constructs the lambda on every render:</p><pre>const loadUsers = () =&gt; {<br>    setLoading(true)<br>}</pre><p>3. Parent depends on a state piece that changes by the child component directly:</p><pre>const users = useSelector(selectUsers)</pre><p>This will re-render when the users state changes, causing #2 to be recomputed, passing it down to #1, causing a new network call to load users, which then in turn calls the selector here again infinitely in a loop.</p><p>To fix this, wrap loadUsers in useCallback in the Parent component</p><pre>const loadUsers = useCallback(() =&gt; {<br>  setLoading(true)<br>}, [setLoading])</pre><p>This ensures only one instance gets passed down. This is not ideal as every parent component to our child component <em>must</em> remember to memoize the functions.</p><p><strong>Good Practice 101: </strong>Always wrap functions declared inside your functional component with useCallback. This will ensure efficiency.</p><h3>useRef vs useState</h3><p>useRef is used to easily capture a value so we can perform an action on them as needed. For example, we can use them to focus an input element:</p><pre>function TextInputWithFocusButton() {<br>  const inputEl = useRef(null);<br>  const onButtonClick = () =&gt; {<br>    // `current` points to the mounted text input element<br>    inputEl.current.focus();<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;input ref={inputEl} type=&quot;text&quot; /&gt;<br>      &lt;button onClick={onButtonClick}&gt;Focus the input&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>This is great, however there is a gotcha. When the reference is set, useRef does not trigger a re-render in your component. Where this may be useful is when we want to grab the clientHeight of a specific component and adjust the UI based on it:</p><pre>const bottomContainerRef = useRef&lt;HTMLDivElement&gt;(null)</pre><pre>&lt;HorizontalSpacer<br>  background={COLORS.<em>PaleGrey</em>}<br>  height={(bottomContainerRef &amp;&amp; bottomContainerRef.clientHeight) || 0} /&gt;</pre><p>This will always be set to 0 as when the first render pass happens, we do not have a ref quite yet.</p><p>To fix this, we need to change the useRef to a useState and then the UI will re-render as expected!</p><pre>const [bottomContainerRef, setBottomContainerRef] = useState&lt;HTMLDivElement | null&gt;(null)</pre><h3>State Objects with useState</h3><p>useState has opened doors to function components that were only available to class components. We typically had a state object as follows:</p><pre>state: State = { <br>  userName: &#39;&#39;,<br>  password: &#39;&#39;,<br>}</pre><p>When we want to update the field input for userName we do:</p><pre>const updateUserName = (value: string) =&gt; setState({ userName: value })</pre><p>This version of setState diffs the object tree and re-renders the component.</p><p>When we useState:</p><pre>const [{ userName, password }, setState] = useState({ <br>  userName: &#39;&#39;,<br>  password: &#39;&#39;,<br>})</pre><pre>const updateUserName = useCallback((value: string) =&gt; {<br>  setState({ userName: value })<br>}, [setState])</pre><p>If state is currently:</p><pre>userName: ‘Andrew’<br>password: ‘fluff’</pre><p>Then we call updateUserName(&#39;Andy&#39;) , our state results in:</p><pre>userName: &#39;Andy&#39;<br>password: undefined</pre><p>In fact, in Typescript this would not even compile. What happens here is that useState does a pure swap and <em>not</em> a diff. One potential solution is to pass the existing object before modifying it:</p><pre>const updateUserName = useCallback((value: string) =&gt; {<br>  setState({ ...state, userName: value })<br>}, [setState, state])</pre><h3>Conclusion</h3><p>“With great power comes great responsibility”</p><p>Know your hooks and watch out for gotchas! They are a double-edged sword in that while they provide significant convenience, power, and responsibility rolled up into a great package, they also have internal complexities and gotchas you need to still be aware of.</p><p>Consult the online <a href="https://reactjs.org/docs/hooks-intro.html">documentation</a> on hooks. Ensure you are using them with performance in mind. When in doubt, console.log!</p><p>I hope you enjoyed this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8fcd25cc1b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzz/react-hooks-gotchas-b8fcd25cc1b6">React Hooks — Gotchas</a> was originally published in <a href="https://medium.com/fuzz">Fuzz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Features You Should Use Now]]></title>
            <link>https://medium.com/fuzz/kotlin-features-you-should-use-now-62d246d80a53?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d246d80a53</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Mon, 30 Apr 2018 18:43:04 GMT</pubDate>
            <atom:updated>2018-04-30T19:45:10.041Z</atom:updated>
            <content:encoded><![CDATA[<p>A little less than a year ago at Google IO 2017, Google announced that Kotlin was a first-class supported language for Android development. It was one of the top highlights of the conference among many other important announcements. I was there and I can tell you that it received the loudest applause.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kmP_1Q9Nwj4WzF0qPAjBQ.jpeg" /></figure><p>Finally, a language on par with Swift, C#, etc.</p><p>Almost one year later, now that we’ve seen, tried, and used Kotlin in some fashion. The language adds a lot of new features when compared with Java, that will improve your code readability and maintainability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2cucaYI-CUvxHml-omgyA.png" /></figure><p>In this post, we will skip the basics of the language and dive right into some interesting features. Read the <a href="https://kotlinlang.org/docs/reference/">reference</a> later if you want even more context.</p><p>In this post, we use Kotlin 1.2.31.</p><h3><strong>Breakdown</strong></h3><p><a href="https://medium.com/fuzz/kotlin-features-you-should-use-now-62d246d80a53#c59c">Sealed Classes</a></p><p><a href="https://medium.com/fuzz/kotlin-features-you-should-use-now-62d246d80a53#7cdd">Inline Methods</a></p><p><a href="https://medium.com/fuzz/kotlin-features-you-should-use-now-62d246d80a53#7e17">Extensions</a></p><h3><strong>Sealed Classes</strong></h3><p><a href="http://kotlinlang.org/docs/reference/sealed-classes.html"><strong>Sealed Classes</strong></a><strong> </strong>are a special kind of class such that the Kotlin compiler can verify all subtypes during compilation, adding some unique benefits.</p><p>Take this enum State :</p><pre>enum class State {<br>  Loading,<br>  Done,<br>  None<br>}</pre><p>Enums are exhaustive in when expressions (switch in Java). In Kotlin, we can return on expressions or assign a value to one, forcing each branch of the expression to supply a valid value to fulfill the expression return type.</p><pre>fun checkState(state: State): Unit = when (state) { // Unit implied with no return<br>    State.Loading -&gt; {<br><br>    }<br>    State.Done -&gt; {<br><br>    }<br>    State.None -&gt; {<br>        <br>    }<br>}</pre><p>Say we want to add more State values to our app (ex. Error). When using expressions, if we don’t use an else branch, compilation will fail with a proper message:</p><pre>&#39;when&#39; expression must be exhaustive, add necessary &#39;Error&#39; branch or &#39;else&#39; branch instead.</pre><p>For best practices (and prevent undefined behavior) do <em>not</em> supply an else branch. (You’ll thank me later!). Add the State.Error branch and we satisfy the condition.</p><p>Now, we use our enum and are initially happy with it. It covers all of our initial cases and we’re coding along. We discover that in some situations, we need the result that the loading State comes back with, instead of utilizing a separate variable. With JVM enums, this is not quite possible. In Java, enum are static singleton objects that cannot have multiple instances. Furthermore, if you want mutable values on those objects (such as to hold state), you globally change it for all consumers of the enum. This is not ideal for a multithreaded (heck single-threaded) app that can mutate this value in many different places.</p><p>To allow our enumto hold state, but have the compiler verify we covered all cases of an instance, we change the declaration to asealed class:</p><pre>sealed class State</pre><p>Next, we must explicitly declare each case of the old enum as subtypes of the sealed class:</p><pre>sealed class State {<br>    object Loading : State()<br>    object Error : State()<br>    object Done : State()<br>    object None : State()<br>}</pre><p><em>Pro-tip: Option-Enter on the </em><em>State class and select the “Convert To Sealed Class” option. This will take care of preserving backwards compatibility.</em></p><p>Observe how an object subclass of a sealed class preserves call site compatibility:</p><pre>when(state) {<br>  State.Loading -&gt;</pre><p>We don’t need the is operator for State.Loading since it is a singleton and will be the same instance.</p><p>Since these are <em>just </em>now classes, we can change our Done state to hold a result object:</p><pre>data class Done&lt;T&gt;(val result T? = null) : State()</pre><p>Notice that since these are classes, we can also make them object <em>or </em>data class.</p><p>Now in our when statement:</p><pre>fun checkState(state: State) = when (state) {<br>    is State.Done(null) -&gt; { <br>      // can pattern match!<br>    }<br>    is State.Done(true) -&gt; {<br>     // can match on result cases</pre><pre>    }<br>    is State.Done&lt;*&gt; -&gt; {<br>     // other values<br>     // access the result directly via smart casting,<br>     // we lose type arguments in java still.<br>     (state.result as? List&lt;User&gt;)<br>      ?.let { userList -&gt; displayUserList(userList) }<strong><br>    </strong> }</pre><pre>    //...excluded for brevity<br>}</pre><p>We can pattern match on the case and only execute code for which value the State contains.</p><p><strong>Best Practices</strong></p><p><em>Keep Compact</em></p><p>Do not overuse to the point where you have a sealed class for everything.If you have UserLoadingState , ProfileLoadingState , etc. and they follow all similar state pattern, it might be time to consider combining them into a single State class. After all, each declaration is another class which comes with it’s overhead. Strike a healthy balance between generic and specific to keep your codebase clean and lean.</p><p><em>Use Only When Necessary</em></p><p>As with any class, do you really need a ScreenAction() sealed class where it’s only parameter is a String ? Given:</p><pre>sealed class ScreenAction(val name: String) { <br>  object Profile(&quot;Profile)<br>  object Account(&quot;Account&quot;)<br>}</pre><p>As it grows, you add many more classes for each String. If not necessary, just define them as:</p><pre>object ScreenAction {<br>  const val Profile = &quot;Profile&quot;<br>  const val Account = &quot;Account&quot;<br>}</pre><p><em>Keep The Declarations Coupled</em></p><p>Declaring them as inside the outer sealed class will “namespace” them to the type, so you are more aware when using it, where it belongs from.</p><pre>sealed class State {<br>    object Loading : State()<br>}</pre><pre>Loading.State</pre><h3><strong>Inline Methods</strong></h3><p><a href="http://kotlinlang.org/docs/reference/inline-functions.html"><strong>Inline Methods</strong></a><strong> </strong>instruct the compiler to copy + paste code into the call site during compilation. This contains some obvious benefits in that we can reduce overhead of certain methods by providing <em>no-cost</em> helper functions. As we all know on Android, we look for ways to minimize method count impact to keep our precious apps under the 65K method limit.</p><p>Take this innocent looking method here:</p><pre>fun log(tag: String, priority: Int, logMessage: () -&gt; String) {<br>  if (BuildConfig.<em>DEBUG</em>) {<br>    Timber.log(priority, tag, logMessage())<br>  }<br>}</pre><p>We want to log a message to <a href="https://github.com/JakeWharton/timber">Timber</a> only on debug builds, and lazily specify the message so that it only calculates itself (a potentially expensive operation) when it is logged. Note: the Android DEX compiler will strip out code executed in BuildConfig.DEBUG checks in release builds, so this code won’t appear in release.</p><p>Let’s dig into the generated JVM byte-code decompiled into Java:</p><pre>public final class LogKt {<br>  public static final void log(<a href="http://twitter.com/NotNull">@NotNull</a> String tag, int priority, <a href="http://twitter.com/NotNull">@NotNull</a> Function0 logMessage) {<br>    Intrinsics.checkParameterIsNotNull(tag, &quot;tag&quot;);<br>    Intrinsics.checkParameterIsNotNull(logMessage, &quot;logMessage&quot;);<br>    if (BuildConfig.DEBUG) {<br>       Timber.log(priority, tag, new Object[]{logMessage.invoke()});<br>    }<br>  }<br>}</pre><p>Ok, from first glance this looks great! The function parameter is passed into the method and it only gets invoked when build is on debug. I can live with new Object[]{logMessage.invoke} because it it’ll only affect debug builds.</p><p>Let us check out the call site of this method:</p><pre>fun call() {<br>   var name = getGeneratedName()<br>   log(&quot;Tracking Name Calls&quot;, priority = Log.DEBUG) { &quot;This $name is my name.&quot; }<br>   useMyName(name);</pre><pre>}</pre><p>So far, so good. Let’s dig into what gets generated.</p><pre>public static final void call() {<br>  final ObjectRef name = new ObjectRef();<br>  name.element = &quot;MyName&quot;;<br>  log(&quot;Yes&quot;, 3, (Function0)(new Function0() {<br>     // $FF: synthetic method<br>     // $FF: bridge method<br>     public Object invoke() {<br>        return this.invoke();<br>     }</pre><pre>     @NotNull<br>     public final String invoke() {<br>        return &quot;This failed &quot; + (String)name.element;<br>     }<br>  }));<br>}</pre><p>Woah, what is this? It appears that when I call log , it is constructing an ObjectRef and Function0 object at the call site. Add these logs <em>everywhere</em> and you are creating objects that the Android Dex Compiler cannot remove.</p><p><strong>The Power of Inline Functions</strong></p><p>This method, in particular, should be inlined. Adding inline to the definition:</p><pre>inline fun log(tag: String, priority: Int, logMessage: () -&gt; String) {<br>   if (BuildConfig.DEBUG) {<br>       Timber.log(priority, tag, logMessage())<br>   }<br>}</pre><p>Ok we expect the method declaration to change:</p><pre>public static final void log(@NotNull String tag, int priority, @NotNull Function0 logMessage) {<br>  Intrinsics.checkParameterIsNotNull(tag, &quot;tag&quot;);<br>  Intrinsics.checkParameterIsNotNull(logMessage, &quot;logMessage&quot;);<br>  if (BuildConfig.DEBUG) {<br>     Timber.log(priority, tag, new Object[]{logMessage.invoke()});<br>  }</pre><pre>}</pre><p>What? No Change? Also why does it exist in bytecode? This method still gets generated for Java consumers and inter-project usage. If this method signature no longer existed, then these consumers would not be able to reference it publicly.</p><p>The real magic is at the call site of this method:</p><pre>public static final void call() {<br>  Object name = &quot;MyName&quot;;<br>  String tag$iv = &quot;Yes&quot;;<br>  int priority$iv = 3;<br>  if (BuildConfig.DEBUG) {<br>     Object[] var10002 = new Object[1];<br>     byte var9 = 0;<br>     Object[] var8 = var10002;<br>     Object[] var7 = var10002;<br>     String var10 = &quot;This failed &quot; + name;<br>     var8[var9] = var10;<br>     Timber.log(priority$iv, tag$iv, var7);<br>  }<br>}</pre><p>As you can see, no unnecessary objects are created here. No function definition and no multiple object instances created outside the BuildConfig.DEBUG .</p><p>This is pretty much what we wanted.</p><p>You might ask, why not do this for more methods? I would say its up to your discretion, however, inlining occurs some minor cost to compilation speed.</p><p><strong>Best Practices</strong></p><p><em>Use with Lambda Arguments</em></p><p>It works best on lambdas because the compiler can directly inline the body (in most instances). As from earlier, without inlining, there could be serious efficiency costs.</p><p><em>Don’t Use For Everything</em></p><p>Inlining requires a cost and the cost is in the compiler. For every copy-paste, the compiler has to keep track of that method body and paste it in. Also the Kotlin/JVM compiler already optimizes certain methods and may perform some inlining anyways.</p><p><em>Inlining May Not Preserve Line Numbers</em></p><p>If you get a crash in your app or program, the stacktrace may not match up completely with the code that executes. The compiler tries to add proper line number and stack traces into the program, but this does not always line up with the source file.</p><p><em>You Can’t Inline Everything</em></p><p>Lambdas that are stored as values or passed around cannot be inlined. You can declare parameters as noinline in that case. Public inline methods that attempt to access private or internal declarations are not allowed due to possible source incompatibility from the calling module.</p><h3><strong>Extensions</strong></h3><p><a href="http://kotlinlang.org/docs/reference/extensions.html"><strong>Extensions</strong></a><strong> </strong>allow us to resolve a static method / property onto an object that already exists. Meaning, we call the object as if it has the method or property. They are a nice replacement forstatic utility methods.</p><pre>StringUtils.isNullOrEmpty(&quot;someString&quot;)</pre><pre>// vs.<br>&quot;someString&quot;.isNullOrEmpty()</pre><p>Under the hood, this method is just astatic method with the first parameter of the method used as the $receiver$ . When declaring it in Kotlin, we can access the class as if we’re in the body of the method.</p><p>Given a pure Kotlin method:</p><pre>object StringUtils {</pre><pre>fun isNullOrEmpty(value: CharSequence?): Boolean = <br>  value == null || toString().<em>trim </em><strong>{ it </strong>&lt;= &#39; &#39; <strong>}</strong>.<em>isEmpty</em>()<br>}</pre><p>We can use the intention “Convert Parameter to Receiver” by pressing Option-Enter on the value parameter.</p><p>Since we’re just using it as a static method, we can remove the StringUtils object declaration and instead make it top level.</p><pre>@file:JvmName(&quot;StringUtils&quot;) // provide Java support.</pre><pre>inline fun CharSequence?.isNullOrEmpty(): Boolean =<br> this == null || toString().<em>trim </em><strong>{ it </strong>&lt;= &#39; &#39; <strong>}</strong>.<em>isEmpty</em>()</pre><p><strong>There are a few things to note:</strong></p><p>The methods are <em>not</em> accessible via reflection on the object instance, because they are just static methods.</p><pre><em>assert</em>(String::class.<em>java</em>.<em>declaredMethods</em>.<em>find </em><strong>{ <br>  </strong>method <strong>-&gt; </strong>method.<em>name </em>== &quot;isNullOrEmpty&quot; <br><strong>} </strong>!= null) // will fail</pre><p>Since they’re static , they can <em>only</em> access members in visible scope of the method, meaning private , protected, and internal (outside module) members are not usable. Also, extensions <em>cannot hold state.</em> val and var are only allowed with no backing property.</p><p>this is the object CharSequence , but is defined as $receiver$ when debugging.</p><p>They are <em>much</em> easier to discover than static utils methods.</p><p>When typing in the IDE, it will suggest the methods along with actual class methods. How many devs know that a StringHelper , StringUtils , FileUtils , DBUtils , ViewUtils, etc all exist for the object they’re using? Also, if using subtypes, it may not immediately be apparent the utils method exists, causing you to make your own duplicate or implement it a different way.</p><p>They can cleanup a cluttered API without sacrificing readability.</p><pre>var View.visible: Boolean<br>get() = visibility == View.VISIBLE<br>set(value) {<br>  visibility = if (value) View.VISIBLE else View.GONE<br>}</pre><pre>recyclerView.visible = true // so much nicer<br>if (recyclerView.visible)</pre><p><strong>Some Best Practices</strong></p><p><em>Do not overuse extension methods.</em></p><p>-&gt; While they are great for cleaning up APIs, use them only for types you cannot control.</p><p>Do:</p><pre>class Person(val name: String, val age: Int) {</pre><pre>val nameAndAge: String<br>        get() = &quot;$name, $age&quot;<br>}</pre><p>Don’t:</p><pre>class Person(val name: String, val age: Int)<br><br>val Person.<em>nameAndAge</em>: String<br>    get() = &quot;$name, $age&quot;</pre><p>Adding extensions means these are decoupled from the class and if you need to change implementation, extensions can no longer be extensions to access out-of-scope members anyways.</p><p><em>Group Them by Utility Type</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*LqO1-Gpysm8gyqMb.jpg" /><figcaption>Avoid the junk file. <a href="http://honeyishrunkthehouse.blogspot.com/2014/01/junk-drawer.html">Source</a></figcaption></figure><p>Correlate them to Java utility files, but keep them grouped by logical type. StringUtils.kt , FileUtils.kt , ViewUtils.kt , etc.</p><p>Do not mix utility method into one single file with no bearing, like KotlinUtils . Think of avoiding a junk file.</p><p>To recap, sealed classes, inlining, and extensions are features that you should use right now. If you don’t use them, there are hidden performance, code readability, and code maintainability costs. These features will only make you improve as an Android/JVM/JS/Native developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d246d80a53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzz/kotlin-features-you-should-use-now-62d246d80a53">Kotlin Features You Should Use Now</a> was originally published in <a href="https://medium.com/fuzz">Fuzz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make DBFlow as Testable as Room, with Kotlin]]></title>
            <link>https://medium.com/android-news/how-to-make-dbflow-as-testable-as-room-with-kotlin-ab50902428c9?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab50902428c9</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Wed, 19 Jul 2017 19:17:39 GMT</pubDate>
            <atom:updated>2017-07-19T19:17:39.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWIINK3pHGKLhL-_RBFlOA.jpeg" /><figcaption>photo by <a href="https://unsplash.com/@sapegin">Artem Sapegin</a> via unsplash</figcaption></figure><p>In the Android database ORM-space, <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a>-the new guy on the block- is a hot topic and rightfully-so: it focuses on testability via Retrofit-style interface definitions, is supported by the team of Google engineers responsible for the Architectural Components, and is simple to use (it works well with the other components and provides seamless interop).</p><p>I wrote this article to show you can still make your code testable with DBFlow even if the main implementation does not require you do so.</p><p>When creating <a href="https://github.com/Raizlabs/DBFlow">DBFlow</a> I wanted to provide a lightning fast, flexible, and feature-rich library that doesn’t limit developers to how they should implement it. So far I think that has worked. On the other hand, Room is pretty opinionated and wants you to follow a strict set of supported features.</p><p>DBFlow also provides a simple implementation and is supported by an active community. Some of the core motivators behind its design are speed and flexibility via a feature-rich library that doesn’t limit developers to a particular design. So what about testability? A data layer backed by DBFlow can be highly testable if the appropriate design paradigm is used. The flexibility offered by the library often leads newcomers to develop systems that are difficult to test, and hopefully this discussion will help you avoid this problem. Specifically, I will flex some of DBFlow’s muscles and show you how you can imitate Room’s DAO classes to make your app testable with Dagger2.</p><p>Before continuing, I will define some concepts used in this article:</p><p><strong>Entity:</strong> A class that represents the structure of a table. Each corresponding field captured in the class is a column and each instance of the class is a corresponding row in the Database.</p><p><strong>DAO:</strong> Data Access Object. The DAO is an abstraction away from the real implementation that actually interacts with the database.</p><p><strong>Dagger2:</strong> A <a href="https://google.github.io/dagger/">dependency injection framework</a> developed by Google. It uses annotation processing to validate and generate all of the boilerplate normally required.</p><p>Here are the steps to achieve our goal:</p><ol><li>Define our Entities</li><li>Define our DAO</li><li>Build our Database</li><li>Inject our DAO into Dagger2</li></ol><h3>Define our Entities</h3><p>In Room we define:</p><pre>@Entity<br>class User(@PrimaryKey var id: Int, var firstName: String, var lastName: String)</pre><p>With DBFlow we define:</p><pre>@Table(database = AppDatabase::class, allFields = true)<br>class User(@PrimaryKey var id: Int = 0, var firstName: String = &quot;&quot;, var lastName: String = &quot;&quot;)</pre><p>Room is eager, meaning all fields are counted by default, unless you specify @Ignore, while DBFlow is lazy unless you specify allFields=true.</p><p><em>Notice we specify the database class in the </em><em>@Table annotation. With DBFlow, a class can only represent the schema of a table for a single database. In contrast, Room allows a single class with the </em><em>@Entity annotation to represent the table schema across multiple databases.</em></p><h3>DAO</h3><p>Unlike Room, DBFlow does not have a built-in representation for a Data Access Object (DAO). DBFlow provides something similar with theModelAdapter class which is generated for every table in the database. ModelAdapter are responsible for marshaling data between the database and our models. We can mock these classes for testing purposes; however, it is very difficult to do so because there are many methods that use Android-specific DB classes such as ContentValues, DatabaseStatement, FlowCursorand more.</p><p>Enter Room with its DAO inside:</p><pre>@Dao<br>interface UserDao {</pre><pre>    @Query(&quot;SELECT * FROM User&quot;)<br>    fun loadUsers(): List&lt;User&gt;</pre><pre>    @Insert<br>    fun insertUsers(userList: List&lt;User&gt;)</pre><pre>    @Update<br>    fun updateUsers(userList: List&lt;User&gt;)</pre><pre>    @Delete<br>    fun deleteUsers(userList: List&lt;User&gt;)<br>}</pre><p>In this example we have abstracted away any knowledge of the internal workings of the DAO (vs. the ModelAdapter). Now all we have to do is mock this class and supply Mockito doReturn() or other stubbing mechanisms for the methods we care about in the DAO.</p><p>In DBFlow using Kotlin and the DBFlow Kotlin Extensions library, we can produce code that is similar to the class above:</p><pre>interface UserDAO {</pre><pre>    fun loadUsers() = (<em>select from </em>User::class).list</pre><pre>    fun insertUsers(userList: List&lt;User&gt;) <br>      = <em>modelAdapter</em>&lt;User&gt;().insertAll(userList)</pre><pre>    fun updateUsers(userList: List&lt;User&gt;)<br>      = <em>modelAdapter</em>&lt;User&gt;().updateAll(userList)</pre><pre>    fun deleteUsers(userList: List&lt;User&gt;) <br>      = <em>modelAdapter</em>&lt;User&gt;().deleteAll(userList)<br>}</pre><p>From this example and the beauty of default interface definition methods in Kotlin, we can define implementation details in the same concise way that Room provides. Also since DBFlow’s wrapper language is compile-time safe, we get similar benefits to Room’s compile time checking. The only difference here is if the User table was not defined, DBFlow would throw a RuntimeException whereas Room would throw a compile time exception.</p><p>Also instead of using String queries, we utilize the wrapper language in DBFlow which will give us good refactoring and find usages support.</p><p>Room’s DAO do not allow you to run the operations on the main thread by default (with good reason and there’s a <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.Builder.html#allowMainThreadQueries()">workaround</a>). DBFlow has no such restriction, although its encouraged to use async transactions instead:</p><pre>interface UserDAO {</pre><pre>    fun loadUsers() = (<em>select from </em>User::class).async<br>}</pre><p>You might be asking, “What about RX Support?” Room supports Flowable and Publisher. Given this interface method that loads all User:</p><pre>@Dao<br>interface UserDao {</pre><pre>    @Query(&quot;SELECT * FROM User&quot;)<br>    fun loadUsers(): Flowable&lt;List&lt;User&gt;&gt;</pre><pre>}</pre><p>With DBFlow you get support for both RXJava 1 and 2 via add-on artifacts. Using the DBFlow-RX + Kotlin RX extensions library we define our DAO using RXJava2:</p><pre>interface UserDAO {</pre><pre>    fun loadUsers() = (<em>select from </em>User::class).<em>rx</em>()<br>      .observeOnTableChanges()<br>      .observeOn(Schedulers.io()).map <strong>{ it</strong>.queryList() <strong>}<br>}</strong></pre><p>Now that we have our DAO, we build our database.</p><h3>Database</h3><p>To tie the DAO and models together, we must define our database.</p><p>In Room you collect all of the tables and DAOs and define them in a class:</p><pre>@Database(entities = <em>arrayOf</em>(User::class), version = 1)<br>abstract class AppDatabase : RoomDatabase() {</pre><pre>    abstract val userDao: UserDao</pre><pre>}</pre><p>Room only generates code for DAOs and @Entities defined in the database. If you include @Entity or @DAO that do not get used, corresponding implementations are not generated.</p><p>DBFlow, on the other hand, requires @Table to define their database, so there are no empty generated classes, as well. The DAO is not part of the library so we do not need to specify it. With this, the database definition is as simple as possible:</p><pre>@Database(version = 1)<br>object AppDatabase</pre><p>In order to prevent making the database file large with defined entities in DBFlow, I decided to require models to define what database they belong to. Doing it this way ensures every @Table corresponds to a database. However, this means only whole DB’s can be shared across modules, not individual model classes. Conversely, Room’s implementation allows you to reuse models in different databases and different modules.</p><h3>Inject DAO into Dagger2</h3><p>Using <a href="https://google.github.io/dagger/">Dagger2</a> for dependency injection, we can make our apps very testable, while providing dependencies to our classes based on scopes and compile-time verification. I will not walk through setting up Dagger2, but I will mention how we can now inject our DBFlow DAO interface and make our app fully testable.</p><p>Using Dagger2, we can inject our DAO. With Room you might define a module named DBModule that provides our DAO implementations:</p><pre>@Module<br>class DBModule {</pre><pre>  @Provides @Singleton<br>  fun appDatabase(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, &quot;room-db&quot;).build()</pre><pre>  @Provides @Singleton<br>  fun userDAO(db: AppDatabase) = db.userDAO</pre><pre>}</pre><p>With DBFlow it would be slightly different:</p><pre>@Module<br>class DBModule {<br>  <br>  val userDAO<br>    @Provides @Singleton<br>    get() = object : UserDAO {}</pre><pre>}</pre><p>Since DBFlow utilizes a global singleton instance for each database (and takes a database parameter at most operations), we don’t need to pass the DB into the DAO here.</p><p>In this article I am using <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">MVVM (Model-View-ViewModel)</a> as the main paradigm for implementation. This could just as easily work with <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP (Model-View-Presenter)</a>.</p><p>Now we can utilize it in our UserViewModel class:</p><pre>class UserListViewModel<br>@Inject constructor(private val userDAO: UserDAO) : ViewModel() {<br> <br>  fun loadUsers() {<br>  <br>    userDAO.loadUsers().subscribe {<br>     // load up users and listen for changes<br>     // also want to dispose it when you don&#39;t need it anymore</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><p><strong>Note: </strong>I have skipped a lot of the work in making the injection work for ViewModels. There is a really great <a href="https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample">example project here</a> explaining how to inject ViewModels with the Architecture Components library easily.</p><p>With this abstraction, we can easily mock in tests — UserDAO is just an interface.</p><h3>Conclusion</h3><p>You can achieve the same testability as Room when you combine Kotlin and DBFlow into interface definitions. With DBFlow’s flexibility and rich feature-set, you can write testable and amazing apps. It is all up to you to design and implement a testable architecture and I hope this article inspires you.</p><p>For more on mobile development, web, and design, checkout the <a href="http://medium.com/fuzz">Fuzz Medium</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab50902428c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/how-to-make-dbflow-as-testable-as-room-with-kotlin-ab50902428c9">How to Make DBFlow as Testable as Room, with Kotlin</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make DBFlow as Testable as Room, with Kotlin]]></title>
            <link>https://medium.com/fuzz/how-to-make-dbflow-as-testable-as-room-with-kotlin-b1694f3f80ad?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1694f3f80ad</guid>
            <category><![CDATA[dbflow]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Tue, 18 Jul 2017 12:56:05 GMT</pubDate>
            <atom:updated>2017-07-19T13:26:23.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWIINK3pHGKLhL-_RBFlOA.jpeg" /><figcaption>photo by <a href="https://unsplash.com/@sapegin">Artem Sapegin</a> via unsplash</figcaption></figure><p>In the Android database ORM-space, <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a>-the new guy on the block- is a hot topic and rightfully-so: it focuses on testability via Retrofit-style interface definitions, is supported by the team of Google engineers responsible for the Architectural Components, and is simple to use (it works well with the other components and provides seamless interop).</p><p>I wrote this article to show you can still make your code testable with DBFlow even if the main implementation does not require you do so.</p><p>When creating <a href="https://github.com/Raizlabs/DBFlow">DBFlow</a> I wanted to provide a lightning fast, flexible, and feature-rich library that doesn’t limit developers to how they should implement it. So far I think that has worked. On the other hand, Room is pretty opinionated and wants you to follow a strict set of supported features.</p><p>DBFlow also provides a simple implementation and is supported by an active community. Some of the core motivators behind its design are speed and flexibility via a feature-rich library that doesn’t limit developers to a particular design. So what about testability? A data layer backed by DBFlow can be highly testable if the appropriate design paradigm is used. The flexibility offered by the library often leads newcomers to develop systems that are difficult to test, and hopefully this discussion will help you avoid this problem. Specifically, I will flex some of DBFlow’s muscles and show you how you can imitate Room’s DAO classes to make your app testable with Dagger2.</p><p>Before continuing, I will define some concepts used in this article:</p><p><strong>Entity:</strong> A class that represents the structure of a table. Each corresponding field captured in the class is a column and each instance of the class is a corresponding row in the Database.</p><p><strong>DAO:</strong> Data Access Object. The DAO is an abstraction away from the real implementation that actually interacts with the database.</p><p><strong>Dagger2:</strong> A <a href="https://google.github.io/dagger/">dependency injection framework</a> developed by Google. It uses annotation processing to validate and generate all of the boilerplate normally required.</p><p>Here are the steps to achieve our goal:</p><ol><li>Define our Entities</li><li>Define our DAO</li><li>Build our Database</li><li>Inject our DAO into Dagger2</li></ol><h3>Define our Entities</h3><p>In Room we define:</p><pre>@Entity<br>class User(@PrimaryKey var id: Int, var firstName: String, var lastName: String)</pre><p>With DBFlow we define:</p><pre>@Table(database = AppDatabase::class, allFields = true)<br>class User(@PrimaryKey var id: Int = 0, var firstName: String = &quot;&quot;, var lastName: String = &quot;&quot;)</pre><p>Room is eager, meaning all fields are counted by default, unless you specify @Ignore, while DBFlow is lazy unless you specify allFields=true.</p><p><em>Notice we specify the database class in the </em><em>@Table annotation. With DBFlow, a class can only represent the schema of a table for a single database. In contrast, Room allows a single class with the </em><em>@Entity annotation to represent the table schema across multiple databases.</em></p><h3>DAO</h3><p>Unlike Room, DBFlow does not have a built-in representation for a Data Access Object (DAO). DBFlow provides something similar with theModelAdapter class which is generated for every table in the database. ModelAdapter are responsible for marshaling data between the database and our models. We can mock these classes for testing purposes; however, it is very difficult to do so because there are many methods that use Android-specific DB classes such as ContentValues, DatabaseStatement, FlowCursorand more.</p><p>Enter Room with its DAO inside:</p><pre>@Dao<br>interface UserDao {<br><br>    @Query(&quot;SELECT * FROM User&quot;)<br>    fun loadUsers(): List&lt;User&gt;<br><br>    @Insert<br>    fun insertUsers(userList: List&lt;User&gt;)<br><br>    @Update<br>    fun updateUsers(userList: List&lt;User&gt;)<br><br>    @Delete<br>    fun deleteUsers(userList: List&lt;User&gt;)<br>}</pre><p>In this example we have abstracted away any knowledge of the internal workings of the DAO (vs. the ModelAdapter). Now all we have to do is mock this class and supply Mockito doReturn() or other stubbing mechanisms for the methods we care about in the DAO.</p><p>In DBFlow using Kotlin and the DBFlow Kotlin Extensions library, we can produce code that is similar to the class above:</p><pre>interface UserDAO {<br><br>    fun loadUsers() = (<em>select from </em>User::class).list<br><br>    fun insertUsers(userList: List&lt;User&gt;) = <em>modelAdapter</em>&lt;User&gt;().insertAll(userList)<br><br>    fun updateUsers(userList: List&lt;User&gt;) = <em>modelAdapter</em>&lt;User&gt;().updateAll(userList)<br><br>    fun deleteUsers(userList: List&lt;User&gt;) = <em>modelAdapter</em>&lt;User&gt;().deleteAll(userList)<br>}</pre><p>From this example and the beauty of default interface definition methods in Kotlin, we can define implementation details in the same concise way that Room provides. Also since DBFlow’s wrapper language is compile-time safe, we get similar benefits to Room’s compile time checking. The only difference here is if the User table was not defined, DBFlow would throw a RuntimeException whereas Room would throw a compile time exception.</p><p>Also instead of using String queries, we utilize the wrapper language in DBFlow which will give us good refactoring and find usages support.</p><p>Room’s DAO do not allow you to run the operations on the main thread by default (with good reason and there’s a <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.Builder.html#allowMainThreadQueries()">workaround</a>). DBFlow has no such restriction, although its encouraged to use async transactions instead:</p><pre>interface UserDAO {<br><br>    fun loadUsers() = (<em>select from </em>User::class).async<br>}</pre><p>You might be asking, “What about RX Support?” Room supports Flowable and Publisher. Given this interface method that loads all User:</p><pre>@Dao<br>interface UserDao {<br><br>    @Query(&quot;SELECT * FROM User&quot;)<br>    fun loadUsers(): Flowable&lt;List&lt;User&gt;&gt;<br><br>}</pre><p>With DBFlow you get support for both RXJava 1 and 2 via add-on artifacts. Using the DBFlow-RX + Kotlin RX extensions library we define our DAO using RXJava2:</p><pre>interface UserDAO {<br><br>    fun loadUsers() = (<em>select from </em>User::class).<em>rx</em>().observeOnTableChanges()<br>      .observeOn(Schedulers.io()).map <strong>{ it</strong>.queryList() <strong>}<br>}</strong></pre><p>Now that we have our DAO, we build our database.</p><h3>Database</h3><p>To tie the DAO and models together, we must define our database.</p><p>In Room you collect all of the tables and DAOs and define them in a class:</p><pre>@Database(entities = <em>arrayOf</em>(User::class), version = 1)<br>abstract class AppDatabase : RoomDatabase() {<br><br>    abstract val userDao: UserDao<br><br>}</pre><p>Room only generates code for DAOs and @Entities defined in the database. If you include @Entity or @DAO that do not get used, corresponding implementations are not generated.</p><p>DBFlow, on the other hand, requires @Table to define their database, so there are no empty generated classes, as well. The DAO is not part of the library so we do not need to specify it. With this, the database definition is as simple as possible:</p><pre>@Database(version = 1)<br>object AppDatabase </pre><p>In order to prevent making the database file large with defined entities in DBFlow, I decided to require models to define what database they belong to. Doing it this way ensures every @Table corresponds to a database. However, this means only whole DB’s can be shared across modules, not individual model classes. Conversely, Room’s implementation allows you to reuse models in different databases and different modules.</p><h3>Inject DAO into Dagger2</h3><p>Using <a href="https://google.github.io/dagger/">Dagger2</a> for dependency injection, we can make our apps very testable, while providing dependencies to our classes based on scopes and compile-time verification. I will not walk through setting up Dagger2, but I will mention how we can now inject our DBFlow DAO interface and make our app fully testable.</p><p>Using Dagger2, we can inject our DAO. With Room you might define a module named DBModule that provides our DAO implementations:</p><pre>@Module<br>class DBModule {</pre><pre>  @Provides @Singleton<br>  fun appDatabase(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, &quot;room-db&quot;).build()</pre><pre>  @Provides @Singleton<br>  fun userDAO(db: AppDatabase) = db.userDAO</pre><pre>}</pre><p>With DBFlow it would be slightly different:</p><pre>@Module<br>class DBModule {<br>  <br>  val userDAO<br>    @Provides @Singleton<br>    get() = object : UserDAO {}</pre><pre>}</pre><p>Since DBFlow utilizes a global singleton instance for each database (and takes a database parameter at most operations), we don’t need to pass the DB into the DAO here.</p><p>In this article I am using <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">MVVM (Model-View-ViewModel)</a> as the main paradigm for implementation. This could just as easily work with <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP (Model-View-Presenter)</a>.</p><p>Now we can utilize it in our UserViewModel class:</p><pre>class UserListViewModel<br>@Inject constructor(private val userDAO: UserDAO) : ViewModel() {<br> <br>  fun loadUsers() {<br>  <br>    userDAO.loadUsers().subscribe {<br>     // load up users and listen for changes<br>     // also want to dispose it when you don&#39;t need it anymore</pre><pre>    }</pre><pre>  } </pre><pre>}</pre><p><strong>Note: </strong>I have skipped a lot of the work in making the injection work for ViewModels. There is a really great <a href="https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample">example project here</a> explaining how to inject ViewModels with the Architecture Components library easily.</p><p>With this abstraction, we can easily mock in tests — UserDAO is just an interface.</p><h3>Conclusion</h3><p>You can achieve the same testability as Room when you combine Kotlin and DBFlow into interface definitions. With DBFlow’s flexibility and rich feature-set, you can write testable and amazing apps. It is all up to you to design and implement a testable architecture and I hope this article inspires you.</p><p>For more on mobile development, web, and design, checkout the <a href="http://medium.com/fuzz">Fuzz Medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1694f3f80ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzz/how-to-make-dbflow-as-testable-as-room-with-kotlin-b1694f3f80ad">How to Make DBFlow as Testable as Room, with Kotlin</a> was originally published in <a href="https://medium.com/fuzz">Fuzz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Developer’s Take On Google IO Day 2-Part 1]]></title>
            <link>https://medium.com/fuzz/a-developers-take-on-google-io-day-2-part-1-f851e2c646a3?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/f851e2c646a3</guid>
            <category><![CDATA[google-io-2017]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[googleio]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Fri, 19 May 2017 00:27:23 GMT</pubDate>
            <atom:updated>2017-05-19T15:25:59.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Day two of this wonderful conference. A beautiful, high-70’s day. In this post, I am going to recap some of the talks I attended with key takeaways for Android developers in two parts. The list of talks I visited today:</p><p>Part 1</p><p><strong>Architecture Components — Solving The Lifecycle Problem</strong></p><p><strong>Android Wear: What’s new &amp; Best Practices</strong></p><p><strong>What’s New In the Android Support Library</strong></p><p><strong>Architecture Components with Room</strong></p><p>Part 2</p><p><strong>Introduction to Android Instant Apps</strong></p><p><strong>What’s New in Android Design Tools-New features and tools for rapid UI development</strong></p><p><strong>Android Instant Apps Best Practices Fireside Chat</strong></p><p><strong>Speeding up your Android Gradle Builds</strong></p><p><strong>Android Fireside Chat</strong></p><p><strong>Architecture Components — Solving The Lifecycle Problem</strong></p><p>As I mentioned <a href="https://medium.com/fuzz/a-developers-take-on-google-io-day-1-50a39065cc84">yesterday</a>, this talk focused on the LiveData,LifecycleObserver, and ViewModel classes.</p><p>LiveData provides a RXJava-style construct that is fully lifecycle aware (and future integration into the support library). What this means it will auto-dispose itself when the android Activity or Fragment is destroyed:</p><pre>public class LocationLiveData extends LiveData&lt;Location&gt; {<br>    private static LocationLiveData sInstance;<br>    private LocationManager locationManager;<br><br>    @MainThread<br>    public static LocationLiveData get(Context context) {<br>        if (sInstance == null) {<br>            sInstance = new LocationLiveData(context.getApplicationContext());<br>        }<br>        return sInstance;<br>    }<br><br>    private SimpleLocationListener listener = new SimpleLocationListener() {<br>        @Override<br>        public void onLocationChanged(Location location) {<br>            setValue(location);<br>        }<br>    };<br><br>    private LocationLiveData(Context context) {<br>        locationManager = (LocationManager) context.getSystemService(<br>                Context.LOCATION_SERVICE);<br>    }<br><br>    @Override<br>    protected void onActive() {<br>    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);<br>    }<br><br>    @Override<br>    protected void onInactive() {<br>        locationManager.removeUpdates(listener);<br>    }<br>}</pre><p>This comes from their <a href="https://developer.android.com/topic/libraries/architecture/livedata.html">example</a> on the developer website. onActive() gets called when at least one observer gets registered on the LiveData class. onInActive() is called when the last observer is removed. They use location updates as a good example of how LiveData helps to ensure that some <em>fundamental</em> android developer pains are addressed in a standard way:</p><p><strong>No Memory Leaks:</strong> Since LiveData binds to an Activity or Fragment lifecycle, it cleans itself up when its no longer used.</p><p><strong>No crashes due to stopped Activities: </strong>During inactive states of the parent lifecycle observer, changes to LiveData are not sent over until the parent goes back into an active state (i.e. Resumed or Started).</p><p><strong>Up to date data:</strong> When a screen is active again, observers receive the latest up to date data based on current state of the LifecycleOwner.</p><p><strong>Configuration Changes:</strong> When an Activity restores itself from configuration changes, any previously bound observer will get it’s last data state.</p><p><strong>Manual Lifecyle Handling out-the-window:</strong> The fragment or UI layer observes data when it wants to. Automatic handling for subscriptions and observers means happier developers.</p><p>We get all of this without having to use or learn RX in a standard way. The team behind this will also add conversion mechanisms into RXJava so you integrate into this seamlessly.</p><p><strong>Android Wear: What’s new &amp; Best Practices</strong></p><p>In this talk they walked us through some of the new changes coming to Android Wear.</p><ol><li>Android O: apps on wear will be even <em>more</em> restricted in background usage for location. Wear apps not actively open will have all of its services killed and only way to survive process death is using foreground services.</li><li>Complications API: They added API support for text and image drawables for having them properly sized and positioned on different watch faces. This is to replace custom implementations that could get quite complex.</li><li>Android Wear Support Library: Android wear’s UI components are getting open-source into the support library so the main material design components are standardized.</li><li>They provided stats and advice when building apps that need to sync data in the BG or run in the BG: Batch updates on WIFI once a day for large datasets. Only do periodical updates when the app is open. When app is open but idle, use ambient display mode. There is much more to help keep battery life at a maximum.</li></ol><p><strong>What’s New In the Android Support Library</strong></p><p>This talk broke down some of the more major changes an improvements coming to Android Support Library v26.</p><ol><li>Native Fonts as xml resource or downloadable asset. Previously we had to either use custom TextView or DataBinding to properly include different fonts in our app. It took them long enough to address and fix this issue. Also, more interestingly they are supporting shared fonts, which go through Google Play Services! So instead of multiple apps bundling font resources with their APK, we can download them securely and easily when the app needs them. Also on top of that, you can access over 800+ Google Fonts from their shared repository and with a couple of clicks in Android Studio, start using them automatically. No more bundling or fussing with designers as long as they use a standard font, it becomes much easier.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9Et2z2BAE-47ytpx1aHZQ.jpeg" /><figcaption>Not the best photo, but it diagrammed out how shared fonts work.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oU1lb7z9LwXrLBW79qpRVg.jpeg" /><figcaption>You can specify these new downloadable fonts in xml and use them accordingly!</figcaption></figure><p>2. PreferenceDataStore essentially allows you to override how preferences get stored and where they go. So you can share a common interface with standard preferences and do things like store them in the cloud somewhere.</p><p>3. Animation Updates: Have new SpringAnimation and FlingAnimation classes.</p><p>4. SVG Updates: Support for nesting SVG objects into animated vectors and more conversion improvements especially for pathData vector attribute.</p><p>5. Emoji Support Library: Messaging apps with MinSDK 19+can take advantage of forward compatibility with emojis user send to each other. This means that when your friend or family member on an iPhone or higher Android version sends you a newer emoji, EmojiCompat handles the work of rendering the image for you. You don’t need to update the app to get newest emojis. If you don’t use Play Services, you can used the bundled version, which requires manual updates.</p><p><strong>Architecture Components with Room</strong></p><p>Room, a new SQLite Database ORM made by Google aims to reduce a lot of boilerplate for SQLite and provide developers with a great library for Android to use.</p><p>They provided a slide that mentioned other solutions. Shout out to my library, <a href="https://github.com/Raizlabs/DBFlow">DBFlow</a>!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkNQ5K5tHa_afVMEW62Tuw.jpeg" /></figure><p>Some of the highlights of the features include:</p><ol><li>Compile-time validation for SQLite queries using annotation processing.</li><li>You define “Retrofit-esque” interfaces into your data that it uses to generate code for. You can embed values passed into functions by using the :name operator in queries. Cleaner than using annotations.</li><li>Embedded Objects: You can embed the fields of another object into your table by “flattening” it. This is a great idea, and something at one point in time was going to implement for DBFlow, but did not finish it. Time to finish it!</li><li>No Relationships: It discourages relationships and forces you to use Join statements, which is not all that bad of an idea. I always get questions in DBFlow about problems or issues with ForeignKey or @OneToMany collections.</li><li>Observability: It knows the kind of queries you have and can, based on what your queries contain, update data based on those changes. So when you update a User.firstName with value of “Andrew”, if you define a query that relies on that User.firstName, it will update observers into that specific value automatically! Kind of neat.</li><li>Testability: You can test the DB by using in-memory databases easily and so it doesn’t write to disk. Also, it has a migration helper class that allows you to test migration versions automatically. Otherwise if you simply increment database version with a change, it auto-clears your database for you.</li><li>Missing features: No async transactions support, however RXJava2 Flowable seems to work. No SQLite wrapper language. Not sure if that’s a “missing” feature as they plan (they mentioned something like this) on adding support in Android Studio for SQL validation checks while you type queries. No caching. Unless they didn’t cover it, caching can have data issues and that’s probably why they don’t have it. Lazy Cursor support is missing so that models are only converted as their used. I can see combining LiveData with the use of that Cursor to automatically close it.</li></ol><p>Next post, I will continue the rest of the exciting Day 2 of the conference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f851e2c646a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzz/a-developers-take-on-google-io-day-2-part-1-f851e2c646a3">A Developer’s Take On Google IO Day 2-Part 1</a> was originally published in <a href="https://medium.com/fuzz">Fuzz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Developer’s Take On Google IO Day 1]]></title>
            <link>https://medium.com/fuzz/a-developers-take-on-google-io-day-1-50a39065cc84?source=rss-6d9ac5be3d46------2</link>
            <guid isPermaLink="false">https://medium.com/p/50a39065cc84</guid>
            <category><![CDATA[googleio]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[google-io-2017]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Andrew Grosner]]></dc:creator>
            <pubDate>Thu, 18 May 2017 05:37:32 GMT</pubDate>
            <atom:updated>2017-05-19T00:30:19.599Z</atom:updated>
            <content:encoded><![CDATA[<p>Every year, Google brings together thousands of developers, designers, press, etc. to Google IO to learn about new initiatives and projects coming out. This year was no different.</p><p>Yesterday, May 16th was badge pickup day or “Day Zero” of the conference. At 5:30AM I woke up in San Francisco and ventured down to Mountain View to pick up my badge. The seating for the main Google Keynote was first-come-first-serve meaning the earlier I got there, the better seat I’d get.</p><p>Upon approaching the main line, it wrapped around a corner I could not see. I assumed the line was pretty long as this was around 6:30AM. At 7:00AM the line started moving and I was shocked. The line was not long at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKKpholrBYvpBJBv9SW_Zg.jpeg" /></figure><p>As you can see above, it actually was not crowded at all. Not like 2015 in San Francisco’s Moscone Center.</p><p>After what seemed like a very long line, it turned out to be not that bad. For the main keynote, I got placed in Section 101, the closest section to the stage!</p><p><strong>Day 1</strong></p><p>Early this morning on May 17th, I arrived back at Mountain View to attend the main keynote:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nd3x5G6jSMXNDultpLxK5Q.jpeg" /><figcaption>Sundar Pichai, the CEO of Google.</figcaption></figure><p>A lot of topics were mentioned in his part of the keynote. First what I learned is Google is getting <em>scary good</em> at image recognition, AI, and smart devices. They showed an example of a picture of a child playing softball behind a chain link fence. The fence obstructed the view of the child, yet they showed something <em>eerily</em><strong><em> </em></strong>similar to SnapChat’s new magic eraser, except it looked way better.</p><p>Also, they have this new feature called <em>Lens</em> which allows you to easily scan objects using the camera for content and do certain actions on them. They showed how it can recognize flowers, or also scan content on the active camera and help you log into WIFI with passwords displayed, for example.</p><p>There were many other exciting general announcements that you can read on, however in this post, I would like to highlight the major changes coming to Android development, and it has got me <strong>REALLY</strong> excited.</p><p><strong>KOTLIN</strong></p><p>The highlight of the Keynote for us Android developers was now Kotlin is a first-class language for Android! When it was announced you could hear a large gasp in the crowd as it was announced and then immediate roaring applause when the Kotlin slide came up. What this means for developers is that we get a modern, null-safe, and concise language for Android development, putting us on par with Swift for iOS. It’s also 100% interoperable with Java so you can start today and keep existing codebases.</p><p>Later at the Developer Keynote they mentioned their continuing commitment to new Java features. It received a very tepid reaction from the crowd and that could have signaled to anyone in the room how we developers felt about Java support. My guess is within a year at next IO, most of the content will be in Kotlin and most professional Android developers will use it in varying capacities. The remaining 5%, companies with a huge codebase and lots of legacy code, will stick around for awhile and maybe never go away. Most, if not all new Android developers will start with Kotlin. If you are reading this and haven’t tried Kotlin, I highly suggest you read up on the language <a href="http://www.kotlinlang.org/">here</a> and decide for yourself if you want to start using it. For me, I am always moving forward and do not want to get left behind.</p><p><strong>New Android Architecture Components to Speed Up Development</strong></p><p>After both regular and developer keynote, I attended the “Intro to Architecture Components” session. In this session, Google developers explained three distinct problems that they are intending on fixing and making <em>much</em> easier for Android development. They introduced “Architecture Components” which will comprise a set of standard libraries (supposedly more to come) to express opinion on how we should architect applications. First, they agree with most developers that lifecycles are too complex and lead to a lot of spaghetti Activity and Fragment code (given you don’t use a pattern like MVVM or MVP). This library will enable lifecycle-aware components and classes such as LiveData. They abstracted away a common, core lifecycle that LiveData uses to automatically know and call disposal methods without the end developer caring about the Android-specific lifecycle. This is great for testing. Also, they debuted theViewModel class. The ViewModel class provides common functionality for your app to implement the MVVM pattern. If you are using MVVM, this is great! For MVP users, you don’t have to use this library. However, it takes configuration changes into account and persists the ViewModel between these changes and removes their instances for you automatically when they’re no longer needed. Wonderful!</p><p>The second problem the Architecture Components aim to solve is SQLite database storage. They announced Room, a SQLite ORM mapping solution for Android that removes the boilerplate away from SQLite. Currently the main developer webpage for SQLite looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVFhrEDI-cw7OllWkYissg.png" /></figure><p>It’s hard to read, can lead to a lot of mistakes, and is not well maintained. (On a side note, I am doing a talk at a meetup at <a href="https://www.meetup.com/bayareaandroid/events/239670662/">Google Launchpad on Friday</a> about <a href="https://github.com/Raizlabs/DBFlow">DBFlow</a>, a similar, but different library than what they announced). However, what is great about Room, is that it employs a similar strategy to Retrofit in that it has you define interfaces into calls for your data. Also from this you define model classes with annotations, which mirrors other ORM library implementations. It’s great that they <em>finally</em> acknowledged the current state of SQLite, and are finally putting effort into improving it for everyone. An example from the <a href="https://developer.android.com/topic/libraries/architecture/room.html">newly launched website</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1b_ZkMNRi7fwx7KOWy_56g.png" /></figure><p>The final problem Architecture Components aim to solve is supply high level app architecture using the Repository pattern in a standard way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK1hfkMOYQ-G3nLO4Gap-g.jpeg" /></figure><p>This architecture very closely mirrors how my typical app architecture looks, and it does well for the ego :o. In this diagram, from the top to the bottom, the data flow is unidirectional. The Controller only knows about the ViewModel . The ViewModel only knows about the Repository , etc. This way at each stage, you can mock out each component, in a testable way using interfaces or Mockito . More to come in the later days about these components and how they work in-depth.</p><p><strong>Key Takeaways from Today</strong></p><ol><li>Kotlin got the loudest applause. Huge Android developer crowd and likely many are using, wanting to use, or have seen Kotlin in many shapes and forms the past couple years. The largest frustration for us is main design decisions with Java and Android and how verbose and error-prone Java can be.</li><li>The organization is WAY better than in years past. We can <em>finally</em> reserve seats to talks. Two years ago (the last IO at the Moscone Center), the lines were so bad people were attending talks one or two in advance just to have a seat for a future talk they wanted to hear. Then there were lines at each talk where people were waiting to get in, only to realize that people from the previous talk were not leaving their seats. It was bad and greatly diminished my conference experience. This year its like they really listened. Not only can we reserve seats, they added standby lines and saved seats for standby people. Also, they increased the size of the venues so much so, that they are almost have too many seats.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjdU18K1puZCj_amyKhV3g.jpeg" /><figcaption>Almost too much space, but I’d take it.</figcaption></figure><p>3. There are a lot of people. Most of the walkways between talks are packed and it is tough to walk around.</p><p>4. The after party was a great time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51zcUNzGfn_CHo1Bnje0CQ.jpeg" /><figcaption>Street Performers!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrzFQZP5KsbgI4h5Y6rdYw.jpeg" /><figcaption>The Crowds</figcaption></figure><p><a href="https://medium.com/fuzz/a-developers-take-on-google-io-day-2-part-1-f851e2c646a3">Click here to read Day 2!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50a39065cc84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fuzz/a-developers-take-on-google-io-day-1-50a39065cc84">A Developer’s Take On Google IO Day 1</a> was originally published in <a href="https://medium.com/fuzz">Fuzz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>