Reputation: 83
I ran into a problem that onNext cannot contain return, but I need to return the string. The request is made using Retrofit with a factory inside the interface (ApiService).
fun getNameAnimal(name : String) : String {
var nameAnimal = " "
val api = ApiService.create()
api.getAnimal("Cat")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ animal ->
// It works
Log.i(LOG, animal.name)
// It NOT works (empty value)
nameAnimal = animal.name
},
{ error ->
Log.e(LOG, error.printStackTrace())
}
)
return nameAnimal
}
In the logs, the answer comes in the format I need.
The method is in a class that is not an activity or fragment. How can I implement my plan?
Upvotes: 1
Views: 2772
Reputation: 16
An easy and clean way to achieve this would be to use an interface.
interface AnimalCallbacks {
fun onAnimalNameReturned(name: String)
}
class MyAnimal: AnimalCallbacks {
override fun onAnimalNameReturned(name: String) {
//handle logic here
}
}
From here you can pass your interface in the method call and send the result back using the method you defined in the interface.
fun getNameAnimal(name : String, callbacks: AnimalCallbacks) {
var nameAnimal = " "
val api = ApiService.create()
api.getAnimal("Cat")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ animal ->
// It works
Log.i(LOG, animal.name)
// It NOT works (empty value)
nameAnimal = animal.name
callbacks.onAnimalNameReturned(animal.name)
},
{ error ->
Log.e(LOG, error.printStackTrace())
}
)
}
Upvotes: 0
Reputation: 83
fun getNameAnimal(name : String) : Single<String> {
val api = ApiService.create()
return api.getAnimal("Cat")
.map { animal -> animal.name }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
2. In activity or fragment
apiWorkingClassInstance.getNameAnimal()
.subscribe(
{ animalName ->
Log.i(LOG, animalName)
//todo
},
{ error ->
Log.e(LOG, error.printStackTrace())
}
)
Thanks for the tip Alex_Skvortsov
Upvotes: 1