I ran into a problem that OnNext cannot contain RETURN, but I need to return the string.
The request is made using a 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 - & gt;
// IT Works.
Log.i (log, animal.name)
// IT Not Works (Empty Value)
Nameanimal = animal.name.
},
{error - & gt;
Log.e (log, error.printstacktrace ())
}
)
Return Nameanimal
}
In the logs, the answer comes in the format you need.
The method is in a class, which is not activated or fragment.
How can I implement my plan?
Answer 1, Authority 100%
You are probably not fully understanding the principles of operation RX.
RETURN NAMEANIMAL
Rower is performed earlier than the assignment is assigned in the Subscribe function, which is why you do not get the value.
Your code can be rewritten in the following way:
1) There, where this code was before (let’s call this class APIWORKINGCLASS).
Fun GetNameanimal (name: string): Single & lt; String & GT; {
Val API = Apiservice.Create ()
Return API.Getanimal ("Cat")
.map {Animal - & gt; Animal.name}
.subscribeon (Schedulers.io ())
.obServeon (AndroidSchedulers.mainThread ())
}
2) in your fragment / activati.
apiworkingclassInstance.getnameanimal ()
.subscribe (
{AnimalName - & gt;
Log.i (Log, AnimalName)
// Do you do what you need to do with the name of the animal (for example, the conclusion in textView)
},
{error - & gt;
Log.e (log, error.printstacktrace ())
}
)