Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- RX + Retrofit preps
- ------- Dependencies -----------
- //RX
- implementation 'io.reactivex:rxjava:1.3.0'
- implementation 'io.reactivex:rxandroid:1.2.1'
- //Networking
- implementation 'com.squareup.retrofit2:retrofit:2.3.0'
- implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
- implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
- implementation 'com.squareup.okhttp3:okhttp:3.10.0'
- implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
- -------Retrofit setup------------
- //In activity
- private lateinit var myAPI : ApiInterface
- fun setupRetrofit() {
- val okHttpClient = OkHttpClient.Builder()
- .addInterceptor(AuthHeaderReplacer(userStorage))
- .addInterceptor(TokenExpiredInterceptor(context, userStorage))
- .retryOnConnectionFailure(true)
- .build()
- val gsonConverter = GsonConverterFactory.create(GsonBuilder().create())
- val retrofit = Retrofit.Builder()
- .baseUrl(apiUrl)
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .addConverterFactory(gsonConverter)
- .client(okHttpClient)
- .build()
- myAPI = retrofit.create(BinelliRecorderAPI::class.java) // The parameter represents the Interface containing retrofit api calls
- }
- --------- API INTERFACE -----------------
- interface BinelliRecorderAPI {
- @GET("case-categories")
- fun getCaseCategories(): Observable<CaseCategoriesResponse>
- }
- ----------API CALL IN ACTIVITY WITH THE HELP OF RX --------------------
- private fun getDepartmentsFromApi() {
- binelliRecorderAPI.getCaseCategories()
- .subscribeOn(Schedulers.io())
- .observeOn(AndroidSchedulers.mainThread())
- .subscribe({
- departmentsList.clear()
- it.data.forEach {
- departmentsList.add(it.name)
- }
- setupDepartmentsAdapter()
- }, {
- showMessage(
- mainScrollView,
- unsuccessful_submission_view,
- errorText,
- apiErrorHandler.getError(this, it)
- )
- setupDepartmentsAdapter()
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement