Home java How to return the value from OBServable in RXJAVA 2

How to return the value from OBServable in RXJAVA 2

Author

Date

Category

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 ())
    }
  )

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions