title: Kotlin - OkHttp - Return from onResponse
body: <p>I'm new in Android Development and I'm trying to fetch json data from DarkSky API, using OkHttp and GSon. Problem is that I need to somehow return response from onResponse method but it's always null.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>class DarkSky : Callback {
  
      private var url: String? = null
      private var forecast: Forecast? = null
  
      fun fetchJson(lat: Double, long: Double): Forecast? {
          this.url = "${Constants.DARK_SKY_BASE_URL}/${Constants.DARK_SKY_KEY}/$lat,$long?exclude=hourly,flags,offset"
  
          val request = Request.Builder().url(url!!).build()
  
          val client = OkHttpClient()
          client.newCall(request).enqueue(this)
  
  
          return this.forecast // when I debug this its NULL
  
      }
  
  
      override fun onFailure(call: Call, e: IOException) {
          println("error")
      }
  
      override fun onResponse(call: Call, response: Response) {
  
          if (response.isSuccessful) {
              val body = response.body()?.string()
  
              val gson = GsonBuilder().create()
              val forecast = gson.fromJson(body, Forecast::class.java)
  
              parse(forecast)
          }
      }
  
      private fun parse(response: Forecast) {
          this.forecast = response  //when I debug this, it contains data I need.
      }
  
  }
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>Made it work with BlockingQueue. But don't know. Is it a good idea?</p>
  
  <pre><code>class DarkSky {
  
      private var url: String? = null
      private var forecast: Forecast? = null
  
      fun fetchJson(lat: Double, long: Double): ArrayBlockingQueue&lt;Forecast&gt;? {
          this.url = "${Constants.DARK_SKY_BASE_URL}/${Constants.DARK_SKY_KEY}/$lat,$long?exclude=hourly,flags,offset"
  
          val request = Request.Builder().url(url!!).build()
  
          val blockingQueue: ArrayBlockingQueue&lt;Forecast&gt; = ArrayBlockingQueue(1) // &lt;&lt;&lt;
  
          val client = OkHttpClient()
          client.newCall(request).enqueue(object : Callback {
              override fun onFailure(call: Call, e: IOException) {
                  println("error")
              }
  
              override fun onResponse(call: Call, response: Response) {
  
                  if (response.isSuccessful) {
                      val body = response.body()?.string()
  
                      val gson = GsonBuilder().create()
                      val forecast = gson.fromJson(body, Forecast::class.java)
  
                      blockingQueue.add(forecast) // &lt;&lt;&lt;
                  }
              }
          })
  
          return blockingQueue
      }
  
  }
  </code></pre>
  
  <p>Don't want to learn bad practices.</p>