<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Emmanuel Guerra</title>
    <description>The latest articles on Forem by Emmanuel Guerra (@eagskunst).</description>
    <link>https://forem.com/eagskunst</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F213931%2F223d338f-f8b5-495d-a872-944beda40fc0.png</url>
      <title>Forem: Emmanuel Guerra</title>
      <link>https://forem.com/eagskunst</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/eagskunst"/>
    <language>en</language>
    <item>
      <title>Handle your Android app orientation changes in semi-automatic</title>
      <dc:creator>Emmanuel Guerra</dc:creator>
      <pubDate>Fri, 15 May 2020 01:53:17 +0000</pubDate>
      <link>https://forem.com/eagskunst/handle-your-android-app-orientation-changes-in-semi-automatic-5c5n</link>
      <guid>https://forem.com/eagskunst/handle-your-android-app-orientation-changes-in-semi-automatic-5c5n</guid>
      <description>&lt;p&gt;&lt;strong&gt;TLDR&lt;/strong&gt;: Using the power of a shared ViewModel + LiveData (and some debugging to see what is happening) you could listen to orientation changes in any activity/fragment by overriding the &lt;em&gt;onConfigurationChanged&lt;/em&gt; function and observing the new Configuration values.&lt;/p&gt;

&lt;p&gt;When developing an Android application, most teams point to a portrait-only experience, which is good if it fills your needs, but it often limits the user experience and will result of users uninstalling the app.&lt;/p&gt;

&lt;p&gt;Today, I will show you how to manage configuration changes in a reactive way and from both sides: the sensor and from a user interaction.&lt;/p&gt;

&lt;p&gt;The example comes from a pet project I have been working: An app to see Twitch clips from a streamer and download them.&lt;br&gt;
First, let’s see why I needed to listen to orientation changes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Change the orientation if the user pressed a button.&lt;/li&gt;
&lt;li&gt; Update the player’s UI when the orientation changed.&lt;/li&gt;
&lt;li&gt; If leaving the player, the user’s orientation must remain the same it had previously.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The 1st point was easy to do: The Android API provides a function to change the orientation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;And that is. The screen orientation changes, and the app will be in landscape mode.&lt;/p&gt;

&lt;p&gt;The second, however, was trickier since I needed a variable that tell me the current orientation and update the UI in base of that.&lt;/p&gt;

&lt;p&gt;My first approach was to have a variable attached to my fragment. It failed because the user can enter either on landscape or in portrait. So, at start, I needed to know the current configuration.&lt;/p&gt;

&lt;p&gt;I started to dig into the ActivityInfo code to see how many orientations are. Turns out there are &lt;strong&gt;17 different orientations&lt;/strong&gt;. Four of them contains the name &lt;em&gt;PORTRAIT&lt;/em&gt;, so we will start from that. Let’s define an extension function that check is the current activity is in portrait:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun Activity.isInPortrait() = requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;However, I was missing one definition that is the default orientation when you have not locked your screen: &lt;em&gt;UNSPECIFIED&lt;/em&gt;. This is the default orientation of activities if in the manifest we define the &lt;em&gt;configChanges&lt;/em&gt; value and add the &lt;em&gt;orientation&lt;/em&gt; specification.&lt;/p&gt;

&lt;p&gt;This specify the system that we will manually take care of configuration changes. I am using ViewModels and Room so there is no problem with doing it by myself.&lt;br&gt;
On a side note, this also let’s ExoPlayer to behave like in Youtube app: The video does not stop if your orientation changes.&lt;/p&gt;

&lt;p&gt;Now, our function we look like this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fun Activity.isInPortrait() = requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT ||
        requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED //The new orientation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Now the UI updates properly if we enter on PORTRAIT, LANDSCAPE and if an user triggers the full screen mode. &lt;/p&gt;

&lt;p&gt;But we still lack a way of knowing when the configuration changes when the devices is rotated with the sensor. &lt;/p&gt;

&lt;p&gt;After digging through StackOverflow and Github, I knew about the &lt;em&gt;onConfigurationChanged&lt;/em&gt; method. It’s an overridable method of the Activities that receives a Configuration object as a parameter. The configuration object comes with a orientation variable that is an interger with 3 possible values:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;UNSPECIFIED&lt;/em&gt;, &lt;em&gt;LANDSCAPE&lt;/em&gt;, &lt;em&gt;PORTRAIT&lt;/em&gt;. This is exactly what I need! &lt;/p&gt;

&lt;p&gt;I define a simple ViewModel which would update the Configuration object with MutableLiveData. The ViewModel will be created lazily on the activity, and be shared across fragments inside that activity:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class OrientationViewModel: BaseViewModel() {

    private val _configData = MutableLiveData&amp;lt;Configuration&amp;gt;()
    val configData = _configData as LiveData&amp;lt;Configuration&amp;gt;

    fun changeConfiguration(configuration: Configuration?){
        _configData.value = configuration
        Timber.d("New configuration. Orientation: ${configuration?.orientation}")
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Override the &lt;em&gt;onConfigurationChanged&lt;/em&gt; method on my HostActivity:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        orientationViewModel.changeConfiguration(newConfig)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Then, on my fragment that holds the Player, observe the changes:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;orientationViewModel.configData.observe(viewLifecycleOwner, Observer { config -&amp;gt;
            if(config != null){
                updatePlayerView(fullScreenBtn, config.orientation)
                updateWindowMode(config.orientation)
            }
        })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Done! If I set a new orientation with activity?.requestOrientation or the user use the sensor to change to landscape/portrait, the activity will handle the UI changes.&lt;/p&gt;

&lt;p&gt;As for the last problem, a simple line inside the Fragment's &lt;em&gt;onDetach&lt;/em&gt; function will leave the user in their default orientation:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;That’s it! You could check the full project in Github:&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i3JOwpme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-ba8488d21cd8ee1fee097b8410db9deaa41d0ca30b004c0c63de0a479114156f.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/eagskunst"&gt;
        eagskunst
      &lt;/a&gt; / &lt;a href="https://github.com/eagskunst/VideoWorld"&gt;
        VideoWorld
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Repository that contains my tests with Exoplayer and network videos APIs.
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;If you are interested on how to make a custom ExoPlayer controls view, how to download files using WorkManager, building recycler views with Epoxy or anything related to the project, like this article and leave a comment with what you want see next!&lt;/p&gt;

</description>
      <category>android</category>
      <category>kotlin</category>
      <category>mobile</category>
    </item>
    <item>
      <title>Making safe API calls with Retrofit and Coroutines</title>
      <dc:creator>Emmanuel Guerra</dc:creator>
      <pubDate>Sat, 11 Jan 2020 22:36:47 +0000</pubDate>
      <link>https://forem.com/eagskunst/making-safe-api-calls-with-retrofit-and-coroutines-1121</link>
      <guid>https://forem.com/eagskunst/making-safe-api-calls-with-retrofit-and-coroutines-1121</guid>
      <description>&lt;p&gt;After the 2.6.0 release, Retrofit has official support for coroutines. The migration from other adapters (like RxJava) it simple. Just change your interface from:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GET("movie/{category}")
fun getMovieListForCategory(@Path("category") category: String) : Single&amp;lt;MovieListResponse&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;to: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GET("movie/{category}")
suspend fun getMovieListForCategory(@Path("category") category: String) : MovieListResponse
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;An make your call within a CoroutineContext:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GlobalScope.launch {
   val response = movieListApi.getMovieListForCategory(category)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;You can see that instead of using a wrapper around the object, you receive the object itself, which it's pretty helpful but has one disanventage: this does not provide a way to determine an error.&lt;/p&gt;

&lt;p&gt;Of course you could use the classic &lt;em&gt;try-catch&lt;/em&gt;, but writting this for every single call is not optimal and it's a bad solution in the long term. Also, who wants to write a &lt;em&gt;try-catch&lt;/em&gt; for every request?&lt;/p&gt;

&lt;p&gt;That's why I'm showing you the solution I made for my work and personal projects!&lt;/p&gt;

&lt;p&gt;First of all, let's define the problems we have:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We need to make safe calls, so every call needs to be around a &lt;em&gt;try-catch&lt;/em&gt; block.&lt;/li&gt;
&lt;li&gt;We need it to work for every call.&lt;/li&gt;
&lt;li&gt;We need to return something in case the call fails&lt;/li&gt;
&lt;li&gt;We need to somehow emit an error or a message if the call fails.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For the first two problems, we can create an static class or an abstract class that handles the calls. But how do we know what to return? &lt;br&gt;
Since every object is different and we are trying to find a solution for every one, we could use a generic function.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;suspend fun &amp;lt;T&amp;gt; safeApiCall() : T
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;We have now what will be our function. The problem we face now: how to exactly make it work for every interface?&lt;br&gt;
After a lot of thinking, reading from the Retrofit repository and articles in the internet, I remember the powerfulness of Kotlin's &lt;strong&gt;higher order functions!&lt;/strong&gt;&lt;br&gt;
Passing a function as a parameter make the solution work for any interface.&lt;br&gt;
So now, we have this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;suspend inline fun &amp;lt;T&amp;gt; safeApiCall(responseFunction: suspend () -&amp;gt; T): T
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Now, the only thing we need to do is to call &lt;code&gt;responseFunction&lt;/code&gt; around a &lt;em&gt;try-catch&lt;/em&gt; and return it as a parameter. But now we face the 3rd problem. The solution is simple: return a nullable object instead of the non-nullable:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;suspend inline fun &amp;lt;T&amp;gt; safeApiCall(responseFunction: suspend () -&amp;gt; T): T?{
    return try{
            responseFunction.invoke()//Or responseFunction()
           }catch (e: Exception){
            e.printStackTrace()
            null
           }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Done! We have the function that will handle every single call safely. Now, let's see what optimizations we can do and how to inform other classes about the error.&lt;/p&gt;

&lt;p&gt;We will handle 3 types of error: HttpExceptions, SocketTimeoutException and IOExceptions. For this, we will create an enum for easy handling. You could also use Int values if you want to.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum class ErrorType {
    NETWORK, // IO
    TIMEOUT, // Socket
    UNKNOWN //Anything else
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;For the HttpExceptions, let's create a function that gets the error message from the API. Here, you need to check what kind of JSON object use the API for error response and the error codes.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;companion object {
    private const val MESSAGE_KEY = "message"
    private const val ERROR_KEY = "error"
}

fun getErrorMessage(responseBody: ResponseBody?): String {
    return try {
        val jsonObject = JSONObject(responseBody!!.string())
        when {
            jsonObject.has(MESSAGE_KEY) -&amp;gt; jsonObject.getString(MESSAGE_KEY)
            jsonObject.has(ERROR_KEY) -&amp;gt; jsonObject.getString(ERROR_KEY)
            else -&amp;gt; "Something wrong happened"
        }
    } catch (e: Exception) {
        "Something wrong happened"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Now, we are going to create an interface that will be in charge of notifying the errors to the classes that implement it:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface RemoteErrorEmitter {
    fun onError(msg: String)
    fun onError(errorType: ErrorType)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Finally, let's modify our &lt;em&gt;try-catch&lt;/em&gt; block. For optimizations, we would change to coroutine context to &lt;em&gt;Dispatchers.IO&lt;/em&gt; when calling &lt;code&gt;responseFunction&lt;/code&gt; and changing the context to &lt;em&gt;Dispatchers.Main&lt;/em&gt; on the &lt;em&gt;catch&lt;/em&gt; block. We use the Main dispatcher so there are no exceptions from modifying the UI thread.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;suspend inline fun &amp;lt;T&amp;gt; safeApiCall(emitter: RemoteErrorEmitter, crossinline responseFunction: suspend () -&amp;gt; T): T? {
    return try{
        val response = withContext(Dispatchers.IO){ responseFunction.invoke() }
        response
    }catch (e: Exception){
        withContext(Dispatchers.Main){
            e.printStackTrace()
            Log.e("ApiCalls", "Call error: ${e.localizedMessage}", e.cause)
            when(e){
                is HttpException -&amp;gt; {
                    val body = e.response()?.errorBody()
                    emitter.onError(getErrorMessage(body))
                }
                is SocketTimeoutException -&amp;gt; emitter.onError(ErrorType.TIMEOUT)
                is IOException -&amp;gt; emitter.onError(ErrorType.NETWORK)
                else -&amp;gt; emitter.onError(ErrorType.UNKNOWN)
            }
        }
        null
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;We are finally done! Now you have a class that can handle exception on Http calls make with coroutines.&lt;br&gt;
Here's an example on how to use this from a ViewModel:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MovieListViewModel(api: MovieListApi): ViewModel(), RemoteErrorEmitter {
  val movieListLiveData = liveData {
      val response = ApiCallsHandler.safeApiCall(this@MovieListViewModel){
          api.getMovieListForCategory("popular")
       }
      emit(response)
  }
  //RemoteErrorEmitter implementation...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;You can see more examples on a recent app I made:&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/eagskunst" rel="noopener noreferrer"&gt;
        eagskunst
      &lt;/a&gt; / &lt;a href="https://github.com/eagskunst/MoviesApp" rel="noopener noreferrer"&gt;
        MoviesApp
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      An application that show a list of categories, a list of movies,the details of the movie and let the user save it on his own list.
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;



</description>
      <category>android</category>
      <category>kotlin</category>
      <category>retrofit</category>
    </item>
  </channel>
</rss>
