0

I have a basic retrofit setup in kotlin.

val BASE_URL: String = "http://10.0.2.2:5000/"

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
    this.level = HttpLoggingInterceptor.Level.BODY
}

private val client: OkHttpClient = OkHttpClient.Builder().apply {
    this.addInterceptor(interceptor)
}.build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .client(client)
    .build()

val service: Api by lazy {
    retrofit.create(Api::class.java)
}

I want to check if the server I'm fetching my data from is running - if its not I want to fall back on the local DB for basic functionality. I tried something similar at first but there's a couple of things that are wrong with this approach. First of all the request timeout period is 10 seconds long, which is a little bit more than you'd want it to be for an app. Second, well, it doesn't really work, it'll still throw an exception if the server is offline.

fun serverReachable(): Boolean {
    return try {
        GlobalScope.async {
            // call whatever api function here
        }
        true
    } catch (e: Exception) {
        false
    }
}

Is there are quick and dirty version of checking if the server is up?

  • Try this: https://stackoverflow.com/a/8919357/14759470 ... It is not retrofit but could help. – SlothCoding Jan 10 '21 at 13:21
  • I am glad I could help. Maybe edit your answer and give that link as a solution to your question because someone could be searching for it. – SlothCoding Jan 10 '21 at 14:25
  • Does this answer your question? [Checking Host Reachability/Availability in Android](https://stackoverflow.com/questions/8919083/checking-host-reachability-availability-in-android) – Dharman Jan 10 '21 at 19:48

0 Answers0