Retrofit API calls using coroutine and suspend functions for beginners

80 篇文章 5 订阅
16 篇文章 0 订阅

Whether we are experienced or new developers we all must have hands-on with Kotlin. And all of us who have used coroutines must have thought of using it for network calls.

Till now none of the networking libraries completely supported coroutines out of the box, So 

Jake Wharton

 provided a library for supporting retrofit with coroutines. But with the release of Retrofit 2.6 it starts providing coroutine support out of the box which means now retrofit is fully compatible with coroutines and we don’t have to manage things like cancelling API calls and all from now are now it is bound with our coroutines itself from where out API was called.

We will see here how to use coroutines with Retrofit for API calls.

We will be using a demo Api provided for free on ‘https://demo.dataverse.org’.

Firstly we need to add the dependency for both retrofit and coroutines.

Now create a new object named ‘ApiProvider’. This will be used for initializing retrofit client.

Notice that we are creating an object and not a class, because an object in an app holds one instance at a time. So only one instance of our retrofit client is created. Also, values in an object are directly accessible.

Now, inside this object, we will first create a function called ‘getHttpClient’ which will return an instance of ‘OkHttpClient’ which we will be using for logging out request and responses for debugging.

Here we initialize out ‘OkHttpClient’ and told our client to debug every request and response.

Now create a variable named ‘retrofit’ and initialize it using ‘Retrofit.Builder()’, Also add all necessary parameters like ‘baseUrl’, ‘client’ etc.

Here we created a variable of type ‘Retrofit’ which we will be using for creating Retrofit’s instance.

Now create a ‘generic’ function named ‘createService’ in ‘ApiProvider’ object and make it return retrofit’s instance.

Here we passed a ‘Class’ to this function with a ‘generic’ type. This is done so that we can reuse this function if required and can pass an instance of different classed as and when required.

Note: If someone doesn’t know what generic type is, As its name suggests it is generic in nature which means it can accept any type of value and it will change its type accordingly. So if we have multiple classes and want o use the same function we can do that with the help of generic types.

Now as we created our client fr network calls. We will now create an interface for defining our API calls.

So, let's create an interface named ‘ApiService’, Here we will define our API calls along with ‘BaseUrl’.

Create a method called ‘getResult()’ with a parameter value of ‘String’ type, This will be the value which we will be searching for. Also, make this function ‘suspend’ by writing suspend in front of it and make it return ‘Response class with our Data Model’.

It will look like this.

It is a ‘Get’ request, so we have used a ‘@query’ for searching. Along with API endpoint defined inside the ‘@GET()’ annotation.

Out ‘ApiService’ class will now look something like

Here we can see that we have defined a ‘BASE_URL’ variable with the base URL for our API calls inside a ‘companion object’. This is done so that any class/object can access this variable directly.

Now, we will create a ‘data’ class which will be used for parsing our result received from API.

So let’s create a ‘data’ class named ‘SearchResultModel’ which will hold our Data and define all variables inside. Also, as we have a nested structure of our response so we have created some inner ‘data’ classes too. Although it is not the right approach as due to this we can not reuse the same class if required but for this demo, we can skip this.

Now, let’s go to our ‘Activity’ class. Our UI will be composed of 3 widgets, one EditText, one Button and one TextView as shown in the image below.

The ‘EditText’ is responsible for taking user input. ‘Button’ is responsible for calling our API and ‘TextView’ is responsible for displaying the result.

Now, we will declare 2 variables here one for ‘apiService’ and second for our ‘coroutine’.

Now let’s initialize our API service in ‘onCreate()’ method of our app.

 

Now, create a method called ‘validateAndSearch()’ which will validate if the user has entered a ‘query’ to search or not. If true, it will call our API else it will throw an error to enter a valid query to search.

Now, Let’s create another function named ‘searchData()’ which will accept a parameter for our search query.

Inside this function, we will define a ‘Coroutine’. And this ‘Coroutine’ will be used for calling our API.

Now, we will call out API inside this coroutine and will define a local variable for holding it’s result like this.

Now, here all the magic happens as we now used a coroutine for calling our API. Now we only need to manage on which thread it should run on, So we used ‘Dispatchers.IO’ to run our API in a background thread. As our ‘getResult’ method is a suspend function so it will return the result once all processing is done and then any other line of code following this one will be called. So now only one thing is left i.e using our result in our API.

As we all know we can manage UI related things only from the ‘Main’ thread so we will use a function ‘withContext()’ that accepts a parameter which is used to define on which thread the code inside it should be executed. For this, we will be using ‘Dispatchers.Main’ to run everything inside on a ‘Main’ thread.

Our final method will look something like this.

Also, one more thing, If anyone is eager about what will happen if we close the activity while our API is called. Or what to do if we want to cancel our API calls. Then just call ‘.cancel()’ function on the coroutine’s instance and it will automatically cancel all API calls. Use this method in ‘onPause()’ of the activity class to prevent any memory leak and crashes.

So, we can clearly see how easy it is to call our API’s from ‘Retrofit’.

You can clone the code from here to see it working: https://github.com/iambaljeet/RetrofitCoroutine

If you liked this tutorial then please give some claps :).

 

转自:https://medium.com/@ibaljeet/retrofit-api-calls-using-coroutine-and-suspend-functions-for-beginners-e30263f63b9a

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值