Those kotlin handy extensions, Retrofit meet Kotlin and Result

Alejandro Moya
2 min readOct 6, 2018

--

Being an Android and iOS developer is crazy sometimes, you have to deal with the things each platform gives you, the differences, sometimes big, sometimes not, and sometimes they’re similar.

Since Swift and Kotlin appeared, they gave us a way to make these different worlds become closer, more alike, more functional?, more type-safe?, well, you know what i mean… 😝

I’ve used Alamofire in iOS projects many times, it’s so pleasant, the API is awesome, using Result to handle the responses, it makes the code look more readable, i wished this existed in Android but in JAVA everything was Interfaces used as Listeners and all that.

Now with Kotlin we can make that happen, in fact, i did it and will give you an extension that will make retrofit look more like Alamofire, cool isn’t it?

First let’s create a minimal version of Result, here’s the snippet 👇

We are using a sealed class to have a “enum” that can handle the different results, we need to make it generic to pass the types that will come from retrofit. As you can see, each class/case has the parameters that come from the Callback interface.

Next we are going to create the extension that will allow us to use encode in a kotlin/alamofire/result way:

Here we create a new enqueue method that will receive a closure that has Result as the input, we call the original enqueue and then call the result closure sending the expected Result.

Now that we have these in place let’s use them together:

As you can see we don’t need to do the object: Callback { ... and overrides and all that anymore, the types are respected!

Hope you find this extension useful, please let me know if you use it, also leave any comments if you believe i could improve it.

--

--

Alejandro Moya

Mobile developer, Father, geek, this is my first attempt at having a blog, be kind 😄