-
Notifications
You must be signed in to change notification settings - Fork 5
Building API Client
In order to build API clients which will communicate with the backend REST endpoints, we will follow a simple event bus approach with the help of Otto. The boilerplate to call API's has been pushed on commit 0876e80, which contains the file /apis/ApiClient.java as the boilerplate and /apis/MainApiClient.java as the interface to define the URL endpoints. We will use the latter file to define all new endpoints.
As you can see we have already defined a dummy api getAllBooks()
. Defining an API is easy, provide the suitable annotation (@GET
, @POST
etc). Then in application, whenever you need to call the api, follow the following steps :
-
Instantiate otto bus from BusProvider
Bus bus = BusProvider.getInstance().getBus();
-
Register bus in the class to subscribe for callbacks
bus.register(this);
-
Define proper callback identifier key in Config.java
public static final String GET_BOOKS = "getBooks";
-
Start a callback request for a particular model
Callback<List<BookModel>> callback = AppClient.getOttoCallback(Config.GET_BOOKS); AppClient.getApiService(bus).getApi().getAllBooks(callback);
-
Subscribe via model in signature to get results
@Subscribe public void onBooksRetreived(ArrayList<BookModel> books) { // do stuff with books }
-
Subscribe error handler
@Subscribe public void onErrorEvent(RetrofitErrorEvent errorEvent) { switch(errorEvent.accessType) { case Config.GET_BOOKS: // handle error } }
-
Unregister otto bus listener when work is finished. This is very important step in order to properly release subscribers or else other activity subscriber may be fired
bus.unregister(this);