Skip to content

Building API Client

Koustuv Sinha edited this page Jan 25, 2016 · 1 revision

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 :

  1. Instantiate otto bus from BusProvider

    Bus bus = BusProvider.getInstance().getBus();
  2. Register bus in the class to subscribe for callbacks

    bus.register(this);
  3. Define proper callback identifier key in Config.java

    public static final String GET_BOOKS = "getBooks";
  4. Start a callback request for a particular model

    Callback<List<BookModel>> callback = AppClient.getOttoCallback(Config.GET_BOOKS);
    AppClient.getApiService(bus).getApi().getAllBooks(callback);
  5. Subscribe via model in signature to get results

    @Subscribe
    public void onBooksRetreived(ArrayList<BookModel> books) {
      // do stuff with books
    }
  6. Subscribe error handler

    @Subscribe
    public void onErrorEvent(RetrofitErrorEvent errorEvent) {
     switch(errorEvent.accessType) {
      case Config.GET_BOOKS:
        // handle error
      }
    }
  7. 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);
Clone this wiki locally