Android API request easy with Fuel library in Kotlin

Sharing is caring!

In this tutorial, we will learn new networking support library named Fuel. As we have already used some of the famous libraries named Retrofit, Volley and Fast networking Library.

Retrofit has mostly used the library in application development which is given by square. It supports and compatible with Java, Kotlin, and RxJava2 Reactive. Here you can get the detail an example of Retrofit API call with RxJava in Kotlin.  Volley is not maintained for a long time.  Now Android has introduced new Android Architecture component Room persistence library and LiveData for Observing the event and new Activity life cycle.

I already explained about the Room persistence library with Kotlin in my last tutorial. Fuel is the easiest HTTP networking library for Kotlin and Android. it has good support of Reactive RxJava2 and LiveData observing. The most important is that it has divided in the part of dependencies. It means that if you need to use RxJava feature then add a Reactive dependency. Similarly, if want to use Live data support or Gson support you can add easily.

Let’s take one simple uses of this library in our application.  We will load one demo API through this library by using Kotlin. I will take Google gson library for JSON parsing. Very first thing you need to add the relevant dependencies in your build.gradle file.

    compile 'com.github.kittinunf.fuel:fuel:' + rootProject.fuelLibVersion
    compile 'com.github.kittinunf.fuel:fuel-android:' + rootProject.fuelLibVersion
    compile 'com.github.kittinunf.fuel:fuel-rxjava:' + rootProject.fuelLibVersion
    compile 'com.google.code.gson:gson:2.7'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
ext {
    fuelLibVersion = "1.8.0"
}

Kotlin is basically known to remove boilerplate code. For example, earlier we used async task for networking operation which required to write a lot of boilerplate code. And Even async task has own limitation for example memory leak because of two different thread execution. Here you can get detail why a need to take care memory leak?

To avoid a lot of boilerplate code for networking operation, Fuel provides a much better solution. It makes the implementation much easy with Kotlin and Android. You just need to instantiate with FuelManager. Ok, Let’s see an example how is it easy?

Here is API URL -> http://demo2974937.mockable.io/getmyfriends

JSON Response is:

{
  	"user": [{
  		"id": "1",
  		"name": "Raj Amal",
  		"email": "raj.amalw@gmail.com"
  	},{
  		"id": "2",
  		"name": "sunil",
  		"email": "sunil@gmail.com"
  	},{
  		"id": "3",
  		"name": "Awadhesh",
  		"email": "awadesh@gmail.com"
  	},{
  		"id": "4",
  		"name": "Sandy",
  		"email": "sandy@gmail.com"
  	},{
  		"id": "5",
  		"name": "Jitendra",
  		"email": "jda@gmail.com"
  	}]
  }

Now I need to convert this JSON to POJO class for deserializing by using GSON library.

class FriendsApiModel {


    @SerializedName("user")
    @Expose
    var user: List<User>? = null

    class User {

        @SerializedName("id")
        @Expose
        var id: String? = null
        @SerializedName("name")
        @Expose
        var name: String? = null
        @SerializedName("email")
        @Expose
        var email: String? = null

        constructor(id: String?, name: String?, email: String?) {
            this.id = id
            this.name = name
            this.email = email
        }
    }

    class ListDeserializer : ResponseDeserializable<List<FriendsApiModel>> {
        override fun deserialize(content: String) =
                Gson().fromJson<List<FriendsApiModel>>(content, object : TypeToken<List<FriendsApiModel>>() {}.type)
    }
}

Now I have to create the interface for what is operation required in my app. Here I am trying to load this JSON data to List of an Observable sequence.

interface ApiService {
    fun getFriends(): Single<List<FriendsApiModel>>
}

Now I need to implement this API service interface.

object RemoteDataSource : ApiService {

    init {
        FuelManager.instance.basePath = "http://demo2974937.mockable.io/"
        FuelManager.instance.addRequestInterceptor(loggingInterceptor())
    }

    override fun getFriends(): Single<List<FriendsApiModel>> =
                    "getmyfriends"
                    .httpGet()
                    .rx_object(FriendsApiModel.ListDeserializer())
                    .map { it?.component1() ?: throw it?.component2() ?: throw Exception() }
                    .doOnSuccess {
                    }

}

OK, That done. Now I need to call this method to execute.

 override fun getFriendsRemote(): Single<List<FriendsApiModel>> {
       return RemoteDataSource.getFriends()
                .doOnSuccess { saveFriendsIntoDb(it) }
    }

That is done. It makes so simple and very limited code to write for this kind of task.

For more information, it provides much more feature to interact with the application. Here are the details:

  1. Support basic HTTP GET/POST/PUT/DELETE/HEAD/PATCH in a fluent style interface
  2. Support both asynchronous and blocking requests
  3. Download file and Upload file (multipart/form-data)
  4. Cancel in-flight request and Request timeout
  5. Configuration manager by using fuel manager
  6. Debug log / cUrl log
  7. Support response deserialization into plain old object (both Kotlin & Java)
  8. Automatically invoke handler on Android Main Thread when using Android Module
  9. RxJava 2.x support out of the box, Google Components LiveData support, Gson module support

Wrapping Up: With a few lines of code, we’re getting the same result from a very typical operation such as making an API call and get its result. Overall it is good to use in android application with Kotlin or Java. I would be recommended to start to use these features to a better result. Anyhow you are free to use any library as per your requirement.  You can get the full source code from Github.

Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.

Happy coding 🙂

0 0 votes
Article Rating

Similar Posts

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments