Lets set the Retrofit for Action
Let's Start Our retrofit setup
retrofit = "2.11.0"
retrofit = { group ="com.squareup.retrofit2" , name = "retrofit", version.ref = "retrofit" }
Also add the gson converter
retrofit-converter-gson = { group ="com.squareup.retrofit2" , name = "converter-gson", version.ref = "retrofit" }
Now implement in build.gradle
implementation(libs.retrofit)
implementation(libs.retrofit.converter.gson)
Done !!
Lets create a interface
interface ApiInterface {
@GET("/posts")
suspend fun getPosts() : List <Post>
@GET("posts/{id}")
suspend fun getPostById(@Path("id") id: Int): Post
@POST("posts")
suspend fun createPost(@Body newPost: Post): Post
@PUT("posts/{id}")
suspend fun updatePost(@Path("id") id: Int, @Body updatedPost: Post): Post
@DELETE("posts/{id}")
suspend fun deletePost(@Path("id") id: Int): Response<Unit>
}
Also create its usage now
class MainViewModel : ViewModel() {
private val _posts = MutableStateFlow<List<Post>?>(null)
val post = _posts.asStateFlow()
companion object {
private fun getRetrofitService(): ApiInterface {
val retrofit = Retrofit
.Builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ApiInterface::class.java)
}
}
init {
getPosts()
}
fun getPosts() {
viewModelScope.launch(
Dispatchers.IO
) {
_posts.update {
getRetrofitService().getPosts()
}
}
}
}
Done !! test it with your compsable !!
lets have some special cases
Query Parameters
To pass query parameters, use @Query
:
............
0 Comments