Home > other >  Optional parameter in retrofit method
Optional parameter in retrofit method

Time:09-29

I have 2 methods:

@POST("/example")
fun getSomething(@Body string: String)

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String)

Sometimes I have to post with header sometimes without, it works but in my opinion it could be one method especially with kotlin default args.

But something like:

@POST("/example")
fun getSomethingWithHeader(@Body string: String, @Header header: String = "")

will probably send also header but empty.

Is it possible to merge these 2 method into 1 ?

CodePudding user response:

Define the header as nullable like this:

@POST("/example")
fun getSomethingWithHeader(
    @Body string: String, 
    @Header("YourHeader") header: String? = null
)

From https://square.github.io/retrofit/:

If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

CodePudding user response:

I think in Kotlin you can build like this example

CodePudding user response:

Just make the header nullable, It won't be passed as a header argument when it's null

@POST("/example")
fun getSomethingWithHeader(
    @Body string: String, 
    @Header("YourHeader") header: String? = null
)

Then when you call this function in maybe your repository: When you want to include your header

class MyRepository(yourApi: YourApi) {

   fun doSomething(body: String, header: String?) {
       yourApi.getSomethingWithHeader(body, header)
   }
}

Then in your viewmodel

class YourViewModel: ViewModel() {

   //...
   fun getSomethingWithHeader(body: String, header: String?) {
     yourRepository.getSomethingWithHeader(body, header)
   }

}

Then in your activity or fragment

class YourFragment: Fragment() {

   //Create your instance of viewmodel
   private val yourViewModel: YourViewModel by viewModels()

   override fun onCreate(savedInstanceState: Bundle?) {

     //if you want to include header do this
     yourViewModel.getSomethingWithHeader(body, header)

     //if you don't want to include the the header do this
     yourViewModel.getSomethingWithHeader(body)

   }

}
  • Related