Funrab
Funrab

Reputation: 83

How to return value from Observable to Rxjava 2

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

Answers (2)

jacqueterrell
jacqueterrell

Reputation: 16

An easy and clean way to achieve this would be to use an interface.

  1. Create your interface
    interface AnimalCallbacks {
      fun onAnimalNameReturned(name: String)
    }
  1. Have your class implement the interface
    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

Funrab
Funrab

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

Related Questions