androidkotlinretrofitnetworkonmainthread

Retrofit Execute Method Network Error on Main Thread


I have the following code in my fragment, specifically in my onViewCreated:

searchResponse = searchCall.execute()

if (!searchResponse.isSuccessful || searchResponse.body()!!.results!!.isEmpty()) {
    // code
} else {
    getResponse = getCall.execute()
    // more code

    if (!getResponse.isSuccessful || getResponse.body()!!.extendedIngredients!!.isEmpty()) {
        // more code
    } else {
       convertResponse = convertCall.execute()
       // more code
    }
}

Obviously not the entire code, but it's a very simplified version of the basic structure for that block of code. Basically, I'm running three API calls via retrofit and I need them to run one at a time since the getResponse API request depends on the data I get from searchResponse and convertResponse API request depends on the data I get from getResponse. This is why I didn't use Retrofit's enqueue because that runs the API calls asynchronously, whereas I'm trying to run them synchronously. How do I get execute method to work? Righ now I'm getting an android.os.NetworkOnMainThreadException error.


Solution

  • One option would be to use RXJava + Retrofit to chain your API calls.

    Although the most straightforward solution would just be to execute all of your code on another thread. There are numerous ways to achieve this, using Kotlin Coroutines is an option in Android.

    If you're executing the code in a fragment, activity etc:

    viewLifecycleOwner.lifecycleScope.launch {
    
        searchResponse = searchCall.execute()
    
        ...
    
    }