0

I'm trying to learn to use Rxjava to make Api calls with retrofit. I have to make multiple api calls in a loop. I'm struggling with getting the value in my subscriber.

@GET("pokemon" + "/{id}")
fun getPokemonData(@Path("id") id: Int):
        Observable<Pokemon>

I'm expecting to get a Pokemon object in my Subscriber but instead I get a Observable. How do I transform it to a Pokemon object?

  Observable.fromIterable(list)
        .flatMap { it ->
            Observable
                .just(it.url)
                .map { PokeApi.retrofitService.getPokemonData(getPokemonIdFromUrl(it))
                }
        }
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
                //onNext --I'm expecting to get a Pokemon Object here, instead I get a Observable<Pokemon>

        }, {//onError} , {// do something when all api calls are done?})

My goal is to make api calls with ids in the "list" and get "notified" when all the api calls are finished. Is this the correct approach to solve this problem ?

2
  • what's list? At first sight, you shouldn't be experiencing what you describe. Commented Oct 5, 2020 at 6:46
  • list is a List<PokemonApiCallUrls> object type. where PokemonApiCallUrls is data class PokemonApiCallUrls(val url: String) Commented Oct 5, 2020 at 13:18

1 Answer 1

1

The problems lies here:

Observable
   .just(it.url)
   .map { PokeApi.retrofitService.getPokemonData(getPokemonIdFromUrl(it)) }

When you use map it maps to the return object from getPokemonData. You probably want to flatMap it:

Observable
   .just(it.url)
   .flatMap { PokeApi.retrofitService.getPokemonData(getPokemonIdFromUrl(it)) }

which not only maps the result but flattens it too so you don't get an observable, but the result of that observable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.