RxKotlin with Retrofit

In Android, we can use RxAndroid in addition to RxKotlin for added Android flavors and benefits, and Retrofit supports them as well.

So, let's start by modifying our build.gradle in favor of ReactiveX. Add the following dependencies to the app level build.gradle:

    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0 ' 
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1' 
    implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0' 

The first one will provide Retrofit 2 Adapters for RxJava 2, while the following two add RxAndroid and RxKotlin to the project.

Note that RxKotlin is a wrapper on top of RxJava, so adapters for RxJava 2 will work perfectly with RxKotlin 2.

Now that we have added the dependencies, let's move on by modifying our code to work with Observable/Flowable instead of Call.

This is the modified APIClient.kt file:

    class APIClient { 
      private var retrofit: Retrofit? = null 
      enum class LogLevel { 
        LOG_NOT_NEEDED, 
        LOG_REQ_RES, 
        LOG_REQ_RES_BODY_HEADERS, 
        LOG_REQ_RES_HEADERS_ONLY 
      }  
      /** 
       * Returns Retrofit builder to create 
       * @param logLevel - to print the log of Request-Response 
       * @return retrofit 
       */ 
      fun getClient(logLevel: Int): Retrofit { 
 
        val interceptor = HttpLoggingInterceptor() 
        when(logLevel) { 
            LogLevel.LOG_NOT_NEEDED -> 
                interceptor.level = HttpLoggingInterceptor.Level.NONE 
            LogLevel.LOG_REQ_RES -> 
                interceptor.level = HttpLoggingInterceptor.Level.BASIC 
            LogLevel.LOG_REQ_RES_BODY_HEADERS -> 
                interceptor.level = HttpLoggingInterceptor.Level.BODY 
            LogLevel.LOG_REQ_RES_HEADERS_ONLY -> 
                interceptor.level =
HttpLoggingInterceptor.Level.HEADERS } val client = OkHttpClient.Builder().connectTimeout(3,
TimeUnit.MINUTES) .writeTimeout(3, TimeUnit.MINUTES) .readTimeout(3,
TimeUnit.MINUTES).addInterceptor(interceptor).build() if(null == retrofit) { retrofit = Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory
(RxJava2CallAdapterFactory.create())
.client(client) .build() } return retrofit!! } fun getAPIService(logLevel: LogLevel =
LogLevel.LOG_REQ_RES_BODY_HEADERS) =
getClient(logLevel).create(APIService::class.java) }

This time, we added an OkHttp Logging interceptor (HttpLoggingInterceptor) along with an RxJava adapter. This OkHttp Logging interceptor will help us log requests and responses. Coming back to the RxJava adapters, look at the highlighted code—we added RxJava2CallAdapterFactory as the CallAdapterFactory of the Retrofit client.

We will need to modify the APIService.kt file as well, to make the functions return Observable instead of Call, as shown here:

    interface APIService { 
      @POST(Constants.GET_TODO_LIST) 
      fun getToDoList(): Observable<GetToDoListAPIResponse> 
 
      @POST(Constants.EDIT_TODO) 
      fun editTodo( 
            @Body todo:String 
      ): Observable<BaseAPIResponse> 
 
      @POST(Constants.ADD_TODO) 
      fun addTodo(@Body todo:String): Observable<BaseAPIResponse> 
    }  

All the APIs now return Observable instead of Call. Finally, we are all set to look inside the fetchTodoList() function from TodoListActivity.

    private fun fetchTodoList() { 
      APIClient() 
      .getAPIService() 
      .getToDoList() 
      .subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onNext = { response -> adapter.setDataset(response.data) }, onError = { e-> e.printStackTrace() } ) }

The function does a simple task; it subscribes to the API (Observable from the API) and sets the data to the adapter when it arrives. You should consider adding logic to check the error code before setting the data here, but for now it works quite well. The screenshot of this activity is already shown at the beginning of this chapter, so we will omit it here.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.22.164