Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. RX + Retrofit preps
  2.  
  3. ------- Dependencies -----------
  4.  
  5. //RX
  6. implementation 'io.reactivex:rxjava:1.3.0'
  7. implementation 'io.reactivex:rxandroid:1.2.1'
  8.  
  9. //Networking
  10. implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  11. implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
  12. implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
  13. implementation 'com.squareup.okhttp3:okhttp:3.10.0'
  14. implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
  15.  
  16. -------Retrofit setup------------
  17. //In activity
  18. private lateinit var myAPI : ApiInterface
  19.  
  20. fun setupRetrofit() {
  21. val okHttpClient = OkHttpClient.Builder()
  22. .addInterceptor(AuthHeaderReplacer(userStorage))
  23. .addInterceptor(TokenExpiredInterceptor(context, userStorage))
  24. .retryOnConnectionFailure(true)
  25. .build()
  26. val gsonConverter = GsonConverterFactory.create(GsonBuilder().create())
  27.  
  28. val retrofit = Retrofit.Builder()
  29. .baseUrl(apiUrl)
  30. .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
  31. .addConverterFactory(gsonConverter)
  32. .client(okHttpClient)
  33. .build()
  34. myAPI = retrofit.create(BinelliRecorderAPI::class.java) // The parameter represents the Interface containing retrofit api calls
  35. }
  36.  
  37. --------- API INTERFACE -----------------
  38. interface BinelliRecorderAPI {
  39. @GET("case-categories")
  40. fun getCaseCategories(): Observable<CaseCategoriesResponse>
  41. }
  42.  
  43. ----------API CALL IN ACTIVITY WITH THE HELP OF RX --------------------
  44.  
  45. private fun getDepartmentsFromApi() {
  46. binelliRecorderAPI.getCaseCategories()
  47. .subscribeOn(Schedulers.io())
  48. .observeOn(AndroidSchedulers.mainThread())
  49. .subscribe({
  50. departmentsList.clear()
  51. it.data.forEach {
  52. departmentsList.add(it.name)
  53. }
  54. setupDepartmentsAdapter()
  55. }, {
  56. showMessage(
  57. mainScrollView,
  58. unsuccessful_submission_view,
  59. errorText,
  60. apiErrorHandler.getError(this, it)
  61. )
  62. setupDepartmentsAdapter()
  63. })
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement