Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Last active November 26, 2024 22:49
Show Gist options
  • Save cbeyls/df12d51c427541eaffe1f6686e5480e2 to your computer and use it in GitHub Desktop.
Save cbeyls/df12d51c427541eaffe1f6686e5480e2 to your computer and use it in GitHub Desktop.
A Retrofit ConverterFactory which lazily serializes the RequestBody handled by the next factory to ensure serialization does not occur on the main thread
package be.digitalia.retrofit2
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
/**
* A ConverterFactory which lazily serializes the RequestBody handled by the next factory
* to ensure serialization does not occur on the main thread.
*/
object LazyRequestBodyConverterFactory : Converter.Factory() {
override fun requestBodyConverter(
type: Type,
parameterAnnotations: Array<out Annotation>,
methodAnnotations: Array<out Annotation>,
retrofit: Retrofit
): Converter<*, RequestBody> {
val delegate = retrofit.nextRequestBodyConverter<Any>(
this,
type,
parameterAnnotations,
methodAnnotations
)
return Converter<Any, RequestBody> { value ->
LazyRequestBody {
requireNotNull(delegate.convert(value))
}
}
}
}
class LazyRequestBody(initializer: () -> RequestBody) : RequestBody() {
private val delegate: RequestBody by lazy(initializer)
override fun contentType(): MediaType? = delegate.contentType()
override fun contentLength(): Long = delegate.contentLength()
override fun writeTo(sink: BufferedSink) = delegate.writeTo(sink)
override fun isDuplex(): Boolean = delegate.isDuplex()
override fun isOneShot(): Boolean = delegate.isOneShot()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment