Adam Varhegyi
Adam Varhegyi

Reputation: 9894

Fatal exception with Kotlin Coroutine without proper error message

I'm learning Kotlin Coroutines and I'm trying to build a simple app with some API requests. Unfortunately I've stumbled upon an error which is not really talkative, this is all I have in the logs:

FATAL EXCEPTION: main 
Process: com.tests.myapp, PID: 14743

This is my simple coroutine which would simply call an API endpoint. I've copied the syntax from this tutorial.

  CoroutineScope(Dispatchers.Main).launch {
       API.call().registration();
  }

For Kotlin Coroutines I use this version:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'

And for the networking library I have Retrofit like this:

object API {

    private const val BASE_URL = "http://my-test-url-comes-here.com"

    private val okHttpClient = OkHttpClient()
        .newBuilder()
        .addInterceptor(RequestInterceptor)
        .build()

    private fun getClient(): Retrofit =
        Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()


    fun call(): Endpoints {
      return  getClient().create(Endpoints::class.java)
    }
}

Any insights?

Upvotes: 1

Views: 755

Answers (2)

Rob
Rob

Reputation: 1047

try to use Dispatchers.IO and also I would suggest you to create your api service only once like this and check you manifest file - you should add internet permission to your app, to make network calls

object API {

   private const val BASE_URL = "http://my-test-url-comes-here.com"

   private val okHttpClient = OkHttpClient()
      .newBuilder()
      .addInterceptor(RequestInterceptor)
      .build()

   private val client by lazy {
      Retrofit.Builder()
          .client(okHttpClient)
          .baseUrl(BASE_URL)
          .addConverterFactory(GsonConverterFactory.create())
          .build()
   }


    val api by lazy {
       client.create(Endpoints::class.java)
    }

}

NOTE: the lazy initializer I wrote here is just sample you can also you non-lazy initializer

Upvotes: 0

TG. Kahsay
TG. Kahsay

Reputation: 134

I think you should use Dispatchers.IO because you are calling a functon that uses network. by passing Dispatcher.Main, you are asking coroutinScope to use UI thread. that gives a Network on Main thread Exception. so,

  CoroutineScope(Dispatchers.IO /* replace Main with IO here */).launch {
       API.call().registration();
  }

Upvotes: 1

Related Questions