Created
June 30, 2021 18:15
-
-
Save yamin8000/27d1d36a9530146f169cce9dda43dac4 to your computer and use it in GitHub Desktop.
OkHttp/Retrofit async call with lambda callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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