简体   繁体   中英

Get object value from Observable (RxJava, Retrofit)

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM