https://kotlinlang.org logo
#android
Title
# android
s

Sam

08/28/2020, 2:36 AM
Copy code
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.IOException

/**
 * @author Leo Nikkilä
 * with modifications made by Paulina Sadowska
 */
class CountingRequestBody(private val delegate: RequestBody, private val listener: Listener) : RequestBody() {

    override fun contentType(): MediaType? {
        return delegate.contentType()
    }

    override fun contentLength(): Long {
        return delegate.contentLength()
    }

    override fun writeTo(sink: BufferedSink) {
        try {
            val countingSink = CountingSink(sink)
            val bufferedSink = countingSink.buffer()
            delegate.writeTo(bufferedSink)
            bufferedSink.flush()
        }catch (ex:Exception){
            ex.printStackTrace()
        }
    }

    internal inner class CountingSink(delegate: Sink) : ForwardingSink(delegate) {
        private var bytesWritten: Long = 0

        @Throws(IOException::class)
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            bytesWritten += byteCount
            listener.onRequestProgress(bytesWritten, contentLength())
        }
    }

    interface Listener {
        fun onRequestProgress(bytesWritten: Long, contentLength: Long)
    }

}
Retrofit config
Copy code
inline fun provideLoggingInterceptor(): HttpLoggingInterceptor {
    return if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.NONE
        }
    } else {
        HttpLoggingInterceptor()
    }
}

inline fun provideRequestInterceptor(): RequestInterceptor {
    return RequestInterceptor()
}

inline fun provideOkHttpClient(): OkHttpClient {
    return OkHttpClient.Builder()
            .connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .addNetworkInterceptor(provideRequestInterceptor())
            .addInterceptor(provideLoggingInterceptor())
//            .addNetworkInterceptor(StethoInterceptor())
            .build()
}

inline fun provideRetrofit(baseUrl: String): Retrofit {
    return Retrofit.Builder()
            .client(provideOkHttpClient())
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder()
                    .setLenient()
                    .create()))
            .addCallAdapterFactory(GapoCoroutineCallAdapterFactory())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
}
3 Views