Advertisement
Kostiggig

First library for android (Simple request)

Nov 5th, 2021
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. interface Request<T> {
  2.  
  3. suspend fun make(url: String) : T
  4.  
  5. class StringRequest : Request<kotlin.String> {
  6.  
  7. private data class Post(
  8. @SerializedName("userId")
  9. private val userId: String,
  10. @SerializedName("title")
  11. private val title: String
  12. ) {
  13. fun giveTitle() = title
  14. }
  15.  
  16. private interface Service {
  17.  
  18. @GET("/posts")
  19. fun data() : Call<List<Post>>
  20. }
  21.  
  22.  
  23. override suspend fun make(url: String): String {
  24. val retrofit = Retrofit.Builder()
  25. .baseUrl(url)
  26. .addConverterFactory(GsonConverterFactory.create())
  27. .build()
  28. val service = retrofit.create(Service::class.java)
  29. log("request in my library")
  30. val result = callWrapper(service.data())
  31. return result[0].giveTitle()
  32. }
  33.  
  34. private suspend fun <T> callWrapper(call: Call<T>) : T {
  35. return suspendCoroutine<T> { continuation ->
  36. call.enqueue(object : Callback<T> {
  37. override fun onResponse(call: Call<T>, response: Response<T>) {
  38. continuation.resume(response.body()!!)
  39. }
  40.  
  41. override fun onFailure(call: Call<T>, t: Throwable) {
  42. log("onFailure ${t.message}")
  43. }
  44.  
  45. })
  46. }
  47. }
  48.  
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement