how can i get data from method return value - kotlin

i use kotlin
i want to get data from method
fun Example() : String{
var value : String
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
print("Getting Data Failed")
}
override fun onResponse(call: Call, response: Response) {
value = "aaa"
}
}
return value
}
finally i want to get value..
but Callback function works late
how can i get value data("aaa")

As far as I understood from your question, you want to perform the request synchronously. This can be done with code like:
fun Example(): String {
val response = client.newCall(request).execute()
val value = if (response.isSuccessful()) {
"aaa"
} else {
error("request failed")
}
return value
}

Related

How to get data with passing parameter in android retrofit kotlin

I want to pass String parameter to the interface and get String data processed with String I passed.
But I can't response.isSuccessful == true.
"/danmun/m" is get one String parameter and return String data.
How can I get the processed String data which I passed.
interface Danmun_processing {
#GET("http://118.67.123.8/danmun/m")
fun getDataParam(#Query("param1") param1 : String): Call<String>
}
val danmunProcessing = retrofit.create(Danmun_processing::class.java)
val sentence = "sample string data"
danmunProcessing.getDataParam(sentence).enqueue(object : Callback<String> {
override fun onResponse(
call: Call<String>,
response: Response<String>
) {
if(response.isSuccessful) {
}
else {
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
}
})
I want to get the processed String data with using data I passed.

What is the best way to get data from an API using retrofit when something needs to wait on that data?

I have a retrofit API call but am having trouble getting the data out of it:
This is in a class file that's not a viewModel or Fragment. It's called from the apps main activity view model. I need to be able to get the data from the API and wait for some processing to be done on it before returning the value back the view model. Newer to kotlin and struggling with all the watchers and async functions. The result of this an empty string is the app crashes, because it's trying to access data before it has a value.
From class getData which is not a fragment
private lateinit var data: Data
fun sync(refresh: Boolean = false): List<String> {
var info = emptyList<String>
try {
getData(::processData, ::onFailure)
info = data.info
} catch(e: Throwable){
throw Exception("failed to get data")
}
}
}
return info
}
fun getData(
onSuccess: KFunction1<ApiResponse>?, Unit>,
onFailed: KFunction1<Throwable, Unit>
) {
val client = ApiClient().create(Service.RequestData)
val request = client.getData()
request.enqueue(object : Callback<ApiResponse> {
override fun onResponse(
call: Call<ApiResponse>,
response: Response<ApiResponse>
) {
onSuccess(response.body())
}
override fun onFailure(call: Call<RegistryResponse<GlobalLanguagePack>>, t: Throwable) {
onFailed(Exception("failed to get data"))
}
})
}
private fun processData(body: ApiResponse?) {
requireNotNull(body)
data = body.data
}
```
From appViewModel.kt:
```
fun setUpStuff(context: Context, resources: AppResources) = viewModelScope.launch {
val stuff = try {
getData.sync()
} catch (e: Exception) {
return#launch
}
if (stuff.isEmpty()) return#launch
}
```

Kotlin Type mismatch: inferred type is String but Unit was expected

Im trying to get the return result to return a string, I believe this might be a noob question but I'm very new to kotlin so please don't be harsh. All solutions welcome!
private val client = OkHttpClient()
fun getRequest(id: String) {
val url = "http://localhost:8000/api/v1/discord?discordid=$id"
val request = Request.Builder()
.url(url)
.header("User-Agent", "OkHttp Bot")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("Error: ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
var result = response.body!!.string()
return result
}
}
})
}
onResponse function has no return type. If you trying to return some value it will throw some error.
So if you want do somthing with the response, you can create a method and pass response body as paramter and do anything with that.
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
var result = response.body?.string()?:""
someMethod(result)
}
}
fun someMethod(response:String){
//Update UI here
}

How to return an object from an api-call-function in Kotlin? [duplicate]

How can I return a value after a callback in kotlin, I tried using Thread.sleep but it doesn't work
fun searchColorFromAPI(): Colors {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
if (serviceResponse != null) {
mColors = serviceResponse
}
else {
//buildToast(getString(R.string.null_response))
}
}
else {
//buildToast(getString(R.string.response_unsuccessful))
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
/* buildToast(getString(R.string.error_calling_service))
Log.e(TAG, t?.message)*/
}
})
return mColors
}
Always, the mColors is returned before the onFailure or onResponse because they're asynchronous. Before this code was in MainActivity but I was advised to take off, but now when I try get mColors I get the empty value before and after the onResponse is executed, please I'm still learning Kotlin and Android.
Your problem stems from the fact that Retrofit call is asynchronous, so as soon as you call searchColorFromAPI it returns you mColors but the API call may not have been made yet, so you get the mColors value before API call.
To solve this issue, you can do
Use callback, this will require little modification in your current setup, but the 2nd option is preferable over this. Using callback your function should look like this.
/* Now instead of returning a value, your function takes a function (named callback)
as parameter. when your api call finishes, you can call the callback function and
pass the api response.
*/
fun searchColorFromAPI(callback: (Colors?) -> Unit) {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
/** pass API response to callback */
callback(serviceResponse)
}
else {
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
callback(null)
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
callback(null)
}
})
}
And in your activity declare a function as follows.
// This function will be called when your api call finishes
// and it will give you the api response
fun apiCallback(colors: Colors?){
if(colors == null){
// API Call failed
}
else{
// use colors as returned by API
}
}
And now call to searchColorFromApi should look like this
searchColorFromApi(apiCallback)
Use Live Data, declare following field in your viewmodel, if you are not using viewmodel then declare it in the class which has searchColorFromApi function.
var colors: MutableLiveData<Colors> = MutableLiveData()
and modify your searchColorFromAPI function as follows
fun searchColorFromAPI() {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
if (serviceResponse != null) {
colors.postValue(response.body)
}
}
else {
colors.postValue(null)
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
colors.postValue(null)
}
})
}
and in your activity do following
fun setupObservers(){
yourApiCallingClass.colors.observe(this, Observer {
// this code is called when ever value of color field changes
})
}
You can use live data ,that gets updated once the callback receives ,the same live data is observed by the caller fragment/activity
You can use coroutines to return a value from function which has asyn calls in it.
You can use interface callbacks to activity/ fragment to trigger the updates received from retrofit calls.

Akka-Http: how to timeout a HttpResponse strict entity in a test

Here is my code
import akka.http.javadsl.Http
// some initialization omitted
inline fun <reified T> executeRequest(request: HttpRequest, crossinline onError: (HttpResponse) -> Unit): CompletionStage<T?> {
val unmarshaller = GsonMarshaller.unmarshaller(T::class.java)
return http.singleRequest(request).thenCompose { httpResponse: HttpResponse ->
if (httpResponse.status() == StatusCodes.OK || httpResponse.status() == StatusCodes.CREATED) {
unmarshaller.unmarshal(httpResponse.entity().withContentType(ContentTypes.APPLICATION_JSON), dispatcher, materializer)
} else {
onError(httpResponse) // invoke lambda to notify of error
httpResponse.discardEntityBytes(materializer)
CompletableFuture.completedFuture(null as T?)
}
}
}
class TradingActor(
val materializer: ActorMaterializer,
val dispatcher: ExecutionContextExecutor
): AbstractLoggingActor() {
fun submitNewOrder(request: Request, onFailed: (text: String) -> Unit) {
executeRequest<OrderAnswer>(request) {
it.entity().toStrict(5_000, materializer).thenApply { entity ->
onFailed("API Call Failed")
}
}.thenAccept {
println("OK")
}
}
}
I have to write a test checking that if .entity().toStrict(5_000, materializer) timeout expires then onFailed("API Call Failed") is called. The current code do not call onFailed("") in case of timeout, therefore I want this test.
my test contains
val response = akka.http.javadsl.model.HttpResponse.create()
.withStatus(StatusCodes.OK)
.withEntity("""{'s': 'text'}""")
Mockito.`when`(http.singleRequest(any()))
.then {
CompletableFuture.completedFuture<akka.http.javadsl.model.HttpResponse>(response)
}
but I don;t know how to make toStrict() expire.
As I understand from your question you can create mock object for ResponseEntity and create own implementation for toStrict() method that will have a delay. Something like in example below from here -> Can I delay a stubbed method response with Mockito?.
when(mock.load("a")).thenAnswer(new Answer<String>() {
#Override
public String answer(InvocationOnMock invocation){
Thread.sleep(5000);
return "ABCD1234";
}
});
Than you can set it in your response object.
val response = akka.http.javadsl.model.HttpResponse.create()
.withStatus(StatusCodes.OK)
.withEntity(mockedEntity)