Android – Architecture – How to call API?

Synchronous call

API class

class APIRequest {

    fun getDataByHttpOK(): ArrayList<Item> {
        val apiUrl = "..."
        val httpClientBuilder = OkHttpClient.Builder()
            .readTimeout(1, TimeUnit.DAYS)
        val httpClient = httpClientBuilder.build()
        val request = Request.Builder()
            .url(apiUrl)
            .addHeader("x-api-key", BuildConfig.MIDDLEWARE_APIKEY)
            .build()

        var items = ArrayList<Item>()
        try {
            val response = httpClient.newCall(request).execute()
            if (response.isSuccessful) {
                val records = JSONArray(response.body()?.string())
                ...
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return items
    }
}

API Request

class Presenter(val view: Contract.View) : Contract.Presenter, KoinComponent {

    override fun getData() {
        AsyncAPIRequest().execute()
    }

    inner class AsyncAPIRequest: AsyncTask<Void, Void, ArrayList<Ite m>>() {

        private val apiRequest: APIRequest by inject()

        override fun doInBackground(vararg params: Void?): ArrayList<Item> {
            return apiRequest.getDataByHttpOK()
        }

        override fun onPostExecute(items: ArrayList<Item>) {
            super.onPostExecute(items)
            
            // Do something with "items"
            ...
        }
    }
}

Asynchronous call

API class

class APIRequest {

    fun getDataByHttpOK(callback: GetItemCallback) {
        // Building OkHttp Client
        val apiUrl = "..."
        val httpClientBuilder = OkHttpClient.Builder()
            .readTimeout(1, TimeUnit.DAYS)
        val httpClient = httpClientBuilder.build()

        // Http Get request
        val request = Request.Builder()
            .url(apiUrl)
            .addHeader("x-api-key", BuildConfig.MIDDLEWARE_APIKEY)
            .build()

        // Make a request
        httpClient.newCall(request).enqueue(object: Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback.onError(e)
            }

            override fun onResponse(call: Call, response: Response) {

                var items: ArrayList<Item> = ArrayList()
                try {
                    if (response.isSuccessful) {
                        val records = JSONArray(response.body()?.string())
                        ...
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }

                callback.onSuccess(items)
            }
        })
    }

    interface GetItemCallback {
        fun onSuccess(body: ArrayList<Item>)
        fun onError(error: Throwable?)
    }
}

API request

class Presenter(val view: Contract.FaqView) : Contract.Presenter, KoinComponent {

    private val apiRequest: APIRequest by inject()

    override fun getData() {
        apiRequest.getDataByHttpOK(object: APIRequest.GetItemCallback{
            override fun onSuccess(items: ArrayList<Item>) {
                // Do something with items
                ...
            }

            override fun onError(error: Throwable?) {
            }
        })
    }
}

RxJava2 & Retrofit

Data model

@Parcelize
data class Item(
    val question: String?,
    val answer: String?
) : Parcelable

API class

Interface

interface DataApi {

    @GET("/items")
    fun getItems(): Single<List<Item>>
}

Class

class APIRequest : KoinComponent {
    private val dataApi: DataApi by inject()

    fun getData(callback: GetItemCallback) {
        val subscription = dataApi.getItems()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                callback.onSuccess(response)
            }, { throwable ->
                callback.onError(throwable)
            })
    }

    interface GetItemCallback {
        fun onSuccess(items: List<Item>)
        fun onError(error: Throwable?)
    }
}

API Request

class Presenter(val view: Contract.View) : Contract.Presenter, KoinComponent {

    private val apiRequest: APIRequest by inject()

    override fun getData() {
        view.showProgress()
        apiRequest.getData(object : APIRequest.GetItemCallback {
            override fun onSuccess(items: List<Item>) {
                // Do something with items here
                ...
                view.hideProgress()
            }

            override fun onError(error: Throwable?) {
                view.hideProgress()
            }
        })
    }
}

Be the first to comment

Leave a Reply

Your email address will not be published.


*