0
votes

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 ?

1
what's list? At first sight, you shouldn't be experiencing what you describe. - Fred
list is a List<PokemonApiCallUrls> object type. where PokemonApiCallUrls is data class PokemonApiCallUrls(val url: String) - Mohd Sohail Ahmed

1 Answers

1
votes

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.