Skip to content

Instantly share code, notes, and snippets.

@yamin8000
Created June 30, 2021 18:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamin8000/27d1d36a9530146f169cce9dda43dac4 to your computer and use it in GitHub Desktop.
Save yamin8000/27d1d36a9530146f169cce9dda43dac4 to your computer and use it in GitHub Desktop.
OkHttp/Retrofit async call with lambda callback
package com.github.yamin8000.fare.model
import android.os.Bundle
import com.github.yamin8000.fare.databinding.ActivityMainBinding
import com.github.yamin8000.fare.ui.BaseActivity
import com.github.yamin8000.fare.web.Services
import com.github.yamin8000.fare.web.WEB
class MainActivity : BaseActivity() {
private val binding : ActivityMainBinding by lazy(LazyThreadSafetyMode.NONE) {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.text.setOnClickListener {
val supaBase = WEB(SUPA_BASE_URL).getService(Services.StateService::class.java)
supaBase.getAll().async { throwable, response ->
if (throwable == null && response != null) {
Logger.d(response)
binding.text.text = "$response"
}
}
}
}
fun <T> Call<T>.async(callback : (Throwable?, T?) -> Unit) {
var throwable : Throwable? = null
var result : T? = null
this.enqueue(object : Callback<T> {
override fun onResponse(call : Call<T>, response : Response<T>) {
result = response.body()
callback(throwable, result)
}
override fun onFailure(call : Call<T>, t : Throwable) {
throwable = t
callback(throwable, result)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment