Introducing Ketro - A Network Request Handling Library using LiveData & Retrofit

Chizoba Ogbonna
Chizoba’s Blog
Published in
2 min readAug 13, 2018

Hi there!

Today I’d be telling you about an awesome android library, Ketro, and how you can use it.

Ketro helps you to easily make network requests and handle its response effectively. It makes use of LiveData from Android Jetpack and Retrofit for making network requests.

Advantages

1. Faster development time.

2. Error handling.

3. Plus all the advantages of using LiveData, and Retrofit.

Getting Started…

Include the dependency below in your app’s build.gradle file

implementation 'past3.smilecs.ketro:ketro:1.0.4.2'

Making Network Requests

Ketro provides 2 methods basically for flexibility.

  • doRequest() : LiveData<Wrapper<R>>
  • executeRequest(liveData: MutableLiveData<Wrapper<R>>)

Note: The Wrapper class is from Ketro.

Both methods are similar as they both perform your network operation when called. The difference is that doRequest() returns the LiveData which you would use to observe changes, whereas executeRequest() allows you to pass in a LiveData you are observing.

The latter is useful when querying data that is paginated, as it prevents you from recreating a new LiveData object when querying a new page.

Here are the simple steps…

Step 1: Create a request handler class that extends Ketro’s `GenericRequestHandler<T>` and put your response model as the parameterised type. Also override its abstract method `makeRequest()` which is where you should make your retrofit call. See a sample below:

Step 2: Make the API call by creating an instance of the request handler class you created above, and calling one of the two methods of Ketro.

Error Handling

Ketro makes error handling easier by providing two components:

1. Kobserver - An extension of the Observer class found in Android’s Architecture Components. This class handles success or error responses and provides two abstract methods for both cases. It is advised to use this in place of the Architecture Components Observer class when using Ketro.

Below is an example of how Kobserver is used:

2. ApiErrorHandler - A class that helps maps your server response codes/messages to an Exception. You will need to extend this class to provide your custom error mapping implementation. If you choose not to, a default Exception is returned.

Below is an example of a custom error mapping implementation:

If you choose to create your custom error mapping implementation, you will also need to override ApiErrorHandler your request handler class.

And then you can add an exception check in the onException() method of Kobserver.

Finally…

I hope you have enjoyed this post. Update it with as much components (like ViewModels) to make your code better. You can find the library and a sample app in this repository.

--

--