Retrofit Library in Android

 Retrofit Library 

We use Retrofit Library to communicate with the back-end. Retrofit library creates URIs for the Web services based on the parameters we pass to it, so we can focus on app functionality. 

Using : 

// Retrofit
implementation "com.squareup.retrofit2:retrofit:$version_retrofit"
implementation "com.squareup.retrofit2:converter-scalars:$version_retrofit"

// converter-scalars allows retrofit to return the JSON result as string 


Network Layer 

The API that our ViewModel will use to communicate with our web services. 

Retrofit is a library that creates a network API for our app based on the content from our web services. It fetches data from our web service and route it through a separate converter library that knows how to decode the data and return it in a form of useful objects. 

Retrofit can support any data format returned from our web service with the right converter library and retrofit includes built-in support for libraries that parse popular web data formats such as XML and JSON. 

After supplying retrofit with the right converter libraries, we then can give retrofit an annotated interface to our API. It returns an implementation of that interface that we can call to talk to our web service. 

/**
* A public interface that exposes the [getProperties] method
*/
interface MyApiService {
/**
* Returns a Coroutine [List] of [MarsProperty] which can be fetched with await() if in a Coroutine scope.
* The @GET annotation indicates that the "myservice" endpoint will be requested with the GET
* HTTP method
*/
@GET("myservice") // specify the endpoint
suspend fun getProperties(@Query("filter") type: String): List<MyProperty>
}

It ultimately creates most of our network layer for us, including critical details, such as running the requests on background threads so they don't block the UI. 

We'll begin by initialising a retrofit object that we'll eventually use to build our web services API. 

Retrofit need to have at least two things available to it to build our APIs. 

  • Base URL of our web service. 
  • Converter factory that allows Retrofit to return the server response in a useful format. 

/**
* Use the Retrofit builder to build a retrofit object using a Moshi converter with our Moshi
* object.
*/
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()

next, we'll define an interface that explains how retrofit talks to our web server using HTTP requests. 

Retrofit will create an object that implements our interface with all of the methods that talks to the server, conceptually similar to the way room implements our DAO. 

Then, 

/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
object MyApi {
val retrofitService : MyApiService by lazy { retrofit.create(MyApiService::class.java) }
}


Now we can use this Retrofit object created in our ViewModel class 








Comments

Popular Posts