title: Coroutines to call a REST API -> FATAL EXCEPTION : main
body: <p>I need to fetch some data from a REST API, everything is ok when I'm 4G or wifi connected but when I'm in airplane mode, the app crashes with  :  "E/AndroidRuntime: FATAL EXCEPTION: main" </p>
  
  <p>Before that I have a log (not an error saying : "Skipped 1013 frames!  The application may be doing too much work on its main thread.")</p>
  
  <p>So I suppose fetching the API with no network crashes the app because it's running in the main thread. BUT I'm using coroutines and to me, I'm doing it right :</p>
  
  <p><strong>ViewModel</strong></p>
  
  <pre><code>private val viewModelJob = SupervisorJob()
  private val viewModelScope = CoroutineScope(viewModelJob + Dispatchers.Main)
  init {
          viewModelScope.launch {
              videosRepository.refreshVideos()
          }
      }
  </code></pre>
  
  <p><strong>Repository</strong></p>
  
  <pre><code>suspend fun refreshVideos() {
          withContext(Dispatchers.IO) {
              val playlist = Network.devbytes.getPlaylist().await()
              //database.videoDao().insertAll(*playlist.asDatabaseModel())
          }
      }
  </code></pre>
  
  <p><strong>Service</strong></p>
  
  <pre><code>/**
   * A retrofit service to fetch a devbyte playlist.
   */
  interface DevbyteService {
      @GET("devbytes.json")
      fun getPlaylist(): Deferred&lt;NetworkVideoContainer&gt;
  }
  
  /**
   * Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
   * full Kotlin compatibility.
   */
  private val moshi = Moshi.Builder()
          .add(KotlinJsonAdapterFactory())
          .build()
  
  /**
   * Main entry point for network access. Call like `Network.devbytes.getPlaylist()`
   */
  object Network {
      // Configure retrofit to parse JSON and use coroutines
      private val retrofit = Retrofit.Builder()
              .baseUrl("https://devbytes.udacity.com/")
              .addConverterFactory(MoshiConverterFactory.create(moshi))
              .addCallAdapterFactory(CoroutineCallAdapterFactory())
              .build()
  
      val devbytes: DevbyteService = retrofit.create(DevbyteService::class.java)
  }
  </code></pre>
  
  <p>So the complete chain is :</p>
  
  <p>ViewModel -> coroutine with Dispatchers.Main</p>
  
  <p>that calls Repository -> suspend function that launch a coroutine with Dispatchers.IO</p>
  
  <p>that calls Service -> through object Network, I get a retrofit instance with a getPlaylist() that returns a Deferred, and the call to that method is in the repository with an await()</p>
  
  <p>What am I doing wrong ?</p>