Rxjava - chain observables Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!When do you use map vs flatMap in RxJava?RxJava Fetching Observables In ParallelRxJava: chaining observablesIn RxJava, how to pass a variable along when chaining observables?Difference between Java 8 streams and RxJava observablesAndroid RxJava and chaining of observableschaining multiple Observables sequentiallyRxJava 2 force complete chain with infinite observableRxJava Zip Observable IterablesHow to chain an Observable with a Single in RxJava?

Why wasn't DOSKEY integrated with COMMAND.COM?

Generate an RGB colour grid

A term for a woman complaining about things/begging in a cute/childish way

Can a new player join a group only when a new campaign starts?

What would you call this weird metallic apparatus that allows you to lift people?

What is a fractional matching?

Project Euler #1 in C++

How to install press fit bottom bracket into new frame

How to react to hostile behavior from a senior developer?

Maximum summed subsequences with non-adjacent items

How could we fake a moon landing now?

What do you call the main part of a joke?

How fail-safe is nr as stop bytes?

Using et al. for a last / senior author rather than for a first author

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

How do living politicians protect their readily obtainable signatures from misuse?

What was the first language to use conditional keywords?

The code below, is it ill-formed NDR or is it well formed?

Dating a Former Employee

How often does castling occur in grandmaster games?

How does the math work when buying airline miles?

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

Did Deadpool rescue all of the X-Force?

Why is my ESD wriststrap failing with nitrile gloves on?



Rxjava - chain observables



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!When do you use map vs flatMap in RxJava?RxJava Fetching Observables In ParallelRxJava: chaining observablesIn RxJava, how to pass a variable along when chaining observables?Difference between Java 8 streams and RxJava observablesAndroid RxJava and chaining of observableschaining multiple Observables sequentiallyRxJava 2 force complete chain with infinite observableRxJava Zip Observable IterablesHow to chain an Observable with a Single in RxJava?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Please look at this code:



 Disposable disposable = mcityService.authLogin(request,Utils.prepareHeaders())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resp ->

mCompositeDisposable.add(mcityService.getUserDetails(selectedCity.id,Utils.prepareHeaders(resp.tokenType,resp.accessToken))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userDetails ->

/*process resp and user details*/

));


, throwable ->

process errors
);

mCompositeDisposable.add(disposable);
}


So basically I need to call authLogin, if it succedes, call getUserDetails (some fields from authLogin call results are required), if getUserDetails succeded, chain is finished and I need some additional processing result from both calls. If authLogin fails or getUserDetails fails, error processing should be performed (for example, get http error code or message from throwable).



As my approach works, I know it's not goot approach, how to optimize it? Can I use flatMap operator instead nested observables?



edit: Methods declarations:



public static Map<String, String> prepareHeaders(String tokenType, String accessToken);
Observable<UserDetails> getUserDetails(@Path(value = "cityId", encoded = true) String cityId, @HeaderMap Map<String, String> headers);


Final attempt:



mcityService.authLogin(request, Utils.prepareHeaders())
.concatMap(response ->

final Map<String, String> headers = Utils.prepareHeaders(response.tokenType,response.accessToken);
return mcityService.getUserDetails(selectedCity.id, headers)
.map(userDetails -> new Object()

public AuthResponse ar = response;
public UserDetails ud = userDetails;
);
)
.doOnNext(responseDetails ->

AuthResponse ar = responseDetails.ar;
UserDetails ud = responseDetails.ud;


)
.doOnError(throwable ->


final String message = throwable.getMessage();

);


Results: .doOnNext never called, mcityService.getUserDetails seems to be never called, .doOnError also never called (so there was no error). First mcityService.authLogin call returns Observable<AuthResponse> don't I really need subscribe?










share|improve this question






























    0















    Please look at this code:



     Disposable disposable = mcityService.authLogin(request,Utils.prepareHeaders())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(resp ->

    mCompositeDisposable.add(mcityService.getUserDetails(selectedCity.id,Utils.prepareHeaders(resp.tokenType,resp.accessToken))
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(userDetails ->

    /*process resp and user details*/

    ));


    , throwable ->

    process errors
    );

    mCompositeDisposable.add(disposable);
    }


    So basically I need to call authLogin, if it succedes, call getUserDetails (some fields from authLogin call results are required), if getUserDetails succeded, chain is finished and I need some additional processing result from both calls. If authLogin fails or getUserDetails fails, error processing should be performed (for example, get http error code or message from throwable).



    As my approach works, I know it's not goot approach, how to optimize it? Can I use flatMap operator instead nested observables?



    edit: Methods declarations:



    public static Map<String, String> prepareHeaders(String tokenType, String accessToken);
    Observable<UserDetails> getUserDetails(@Path(value = "cityId", encoded = true) String cityId, @HeaderMap Map<String, String> headers);


    Final attempt:



    mcityService.authLogin(request, Utils.prepareHeaders())
    .concatMap(response ->

    final Map<String, String> headers = Utils.prepareHeaders(response.tokenType,response.accessToken);
    return mcityService.getUserDetails(selectedCity.id, headers)
    .map(userDetails -> new Object()

    public AuthResponse ar = response;
    public UserDetails ud = userDetails;
    );
    )
    .doOnNext(responseDetails ->

    AuthResponse ar = responseDetails.ar;
    UserDetails ud = responseDetails.ud;


    )
    .doOnError(throwable ->


    final String message = throwable.getMessage();

    );


    Results: .doOnNext never called, mcityService.getUserDetails seems to be never called, .doOnError also never called (so there was no error). First mcityService.authLogin call returns Observable<AuthResponse> don't I really need subscribe?










    share|improve this question


























      0












      0








      0








      Please look at this code:



       Disposable disposable = mcityService.authLogin(request,Utils.prepareHeaders())
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(resp ->

      mCompositeDisposable.add(mcityService.getUserDetails(selectedCity.id,Utils.prepareHeaders(resp.tokenType,resp.accessToken))
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(userDetails ->

      /*process resp and user details*/

      ));


      , throwable ->

      process errors
      );

      mCompositeDisposable.add(disposable);
      }


      So basically I need to call authLogin, if it succedes, call getUserDetails (some fields from authLogin call results are required), if getUserDetails succeded, chain is finished and I need some additional processing result from both calls. If authLogin fails or getUserDetails fails, error processing should be performed (for example, get http error code or message from throwable).



      As my approach works, I know it's not goot approach, how to optimize it? Can I use flatMap operator instead nested observables?



      edit: Methods declarations:



      public static Map<String, String> prepareHeaders(String tokenType, String accessToken);
      Observable<UserDetails> getUserDetails(@Path(value = "cityId", encoded = true) String cityId, @HeaderMap Map<String, String> headers);


      Final attempt:



      mcityService.authLogin(request, Utils.prepareHeaders())
      .concatMap(response ->

      final Map<String, String> headers = Utils.prepareHeaders(response.tokenType,response.accessToken);
      return mcityService.getUserDetails(selectedCity.id, headers)
      .map(userDetails -> new Object()

      public AuthResponse ar = response;
      public UserDetails ud = userDetails;
      );
      )
      .doOnNext(responseDetails ->

      AuthResponse ar = responseDetails.ar;
      UserDetails ud = responseDetails.ud;


      )
      .doOnError(throwable ->


      final String message = throwable.getMessage();

      );


      Results: .doOnNext never called, mcityService.getUserDetails seems to be never called, .doOnError also never called (so there was no error). First mcityService.authLogin call returns Observable<AuthResponse> don't I really need subscribe?










      share|improve this question
















      Please look at this code:



       Disposable disposable = mcityService.authLogin(request,Utils.prepareHeaders())
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(resp ->

      mCompositeDisposable.add(mcityService.getUserDetails(selectedCity.id,Utils.prepareHeaders(resp.tokenType,resp.accessToken))
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(userDetails ->

      /*process resp and user details*/

      ));


      , throwable ->

      process errors
      );

      mCompositeDisposable.add(disposable);
      }


      So basically I need to call authLogin, if it succedes, call getUserDetails (some fields from authLogin call results are required), if getUserDetails succeded, chain is finished and I need some additional processing result from both calls. If authLogin fails or getUserDetails fails, error processing should be performed (for example, get http error code or message from throwable).



      As my approach works, I know it's not goot approach, how to optimize it? Can I use flatMap operator instead nested observables?



      edit: Methods declarations:



      public static Map<String, String> prepareHeaders(String tokenType, String accessToken);
      Observable<UserDetails> getUserDetails(@Path(value = "cityId", encoded = true) String cityId, @HeaderMap Map<String, String> headers);


      Final attempt:



      mcityService.authLogin(request, Utils.prepareHeaders())
      .concatMap(response ->

      final Map<String, String> headers = Utils.prepareHeaders(response.tokenType,response.accessToken);
      return mcityService.getUserDetails(selectedCity.id, headers)
      .map(userDetails -> new Object()

      public AuthResponse ar = response;
      public UserDetails ud = userDetails;
      );
      )
      .doOnNext(responseDetails ->

      AuthResponse ar = responseDetails.ar;
      UserDetails ud = responseDetails.ud;


      )
      .doOnError(throwable ->


      final String message = throwable.getMessage();

      );


      Results: .doOnNext never called, mcityService.getUserDetails seems to be never called, .doOnError also never called (so there was no error). First mcityService.authLogin call returns Observable<AuthResponse> don't I really need subscribe?







      java observable rx-java2 flatmap






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 11:34







      user1209216

















      asked Mar 22 at 10:06









      user1209216user1209216

      1,93242464




      1,93242464






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Yes, you can, and should use flatMap / concatMap / switchMap.

          Also, sorry if it is not coded well, I primarily use RxJS, which has pipable operators (much better!).



          mcityService.authLogin(request, Utils.prepareHeaders())
          .concatMap(response ->
          final Map<String, String> headers = Utils.prepareHeaders(resp.tokenType,resp.accessToken);
          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> ResponseUserDetails.of(response, userDetails));
          )
          .doOnNext(responseDetails ->
          // Hanlde ResponseUserDetails object
          )
          .doOnError(throwable ->
                     // Handle exception
          final String message = throwable.getMessage();
          ...
                 )
          .subscribe(
          responseDetails -> ... ,
          throwable -> ...
          );



          If you don't want to use an additional class, you can create an Object on the fly



          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> new Object()
          public Response r = response;
          public UserDetails ud = userDetails;
          );


          And access its fields via



          .doOnNext(responseDetails -> 
          final Response r = responseDetails.r;
          final UserDetails ud = responseDetails.ud;
          ...
          )



          static class ResponseUserDetails 
          final Response response;
          final UserDetails userDetails;

          ResponseUserDetails(
          final Response response,
          final UserDetails userDetails)
          this.response = response;
          this.userDetails = userDetails;


          static ResponseUserDetails of(
          final Response response,
          final UserDetails userDetails)
          return new ResponseUserDetails(response, userDetails);





          enter image description here






          share|improve this answer

























          • Comments are not for extended discussion; this conversation has been moved to chat.

            – Jean-François Fabre
            Mar 22 at 20:59











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55297223%2frxjava-chain-observables%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Yes, you can, and should use flatMap / concatMap / switchMap.

          Also, sorry if it is not coded well, I primarily use RxJS, which has pipable operators (much better!).



          mcityService.authLogin(request, Utils.prepareHeaders())
          .concatMap(response ->
          final Map<String, String> headers = Utils.prepareHeaders(resp.tokenType,resp.accessToken);
          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> ResponseUserDetails.of(response, userDetails));
          )
          .doOnNext(responseDetails ->
          // Hanlde ResponseUserDetails object
          )
          .doOnError(throwable ->
                     // Handle exception
          final String message = throwable.getMessage();
          ...
                 )
          .subscribe(
          responseDetails -> ... ,
          throwable -> ...
          );



          If you don't want to use an additional class, you can create an Object on the fly



          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> new Object()
          public Response r = response;
          public UserDetails ud = userDetails;
          );


          And access its fields via



          .doOnNext(responseDetails -> 
          final Response r = responseDetails.r;
          final UserDetails ud = responseDetails.ud;
          ...
          )



          static class ResponseUserDetails 
          final Response response;
          final UserDetails userDetails;

          ResponseUserDetails(
          final Response response,
          final UserDetails userDetails)
          this.response = response;
          this.userDetails = userDetails;


          static ResponseUserDetails of(
          final Response response,
          final UserDetails userDetails)
          return new ResponseUserDetails(response, userDetails);





          enter image description here






          share|improve this answer

























          • Comments are not for extended discussion; this conversation has been moved to chat.

            – Jean-François Fabre
            Mar 22 at 20:59















          0














          Yes, you can, and should use flatMap / concatMap / switchMap.

          Also, sorry if it is not coded well, I primarily use RxJS, which has pipable operators (much better!).



          mcityService.authLogin(request, Utils.prepareHeaders())
          .concatMap(response ->
          final Map<String, String> headers = Utils.prepareHeaders(resp.tokenType,resp.accessToken);
          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> ResponseUserDetails.of(response, userDetails));
          )
          .doOnNext(responseDetails ->
          // Hanlde ResponseUserDetails object
          )
          .doOnError(throwable ->
                     // Handle exception
          final String message = throwable.getMessage();
          ...
                 )
          .subscribe(
          responseDetails -> ... ,
          throwable -> ...
          );



          If you don't want to use an additional class, you can create an Object on the fly



          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> new Object()
          public Response r = response;
          public UserDetails ud = userDetails;
          );


          And access its fields via



          .doOnNext(responseDetails -> 
          final Response r = responseDetails.r;
          final UserDetails ud = responseDetails.ud;
          ...
          )



          static class ResponseUserDetails 
          final Response response;
          final UserDetails userDetails;

          ResponseUserDetails(
          final Response response,
          final UserDetails userDetails)
          this.response = response;
          this.userDetails = userDetails;


          static ResponseUserDetails of(
          final Response response,
          final UserDetails userDetails)
          return new ResponseUserDetails(response, userDetails);





          enter image description here






          share|improve this answer

























          • Comments are not for extended discussion; this conversation has been moved to chat.

            – Jean-François Fabre
            Mar 22 at 20:59













          0












          0








          0







          Yes, you can, and should use flatMap / concatMap / switchMap.

          Also, sorry if it is not coded well, I primarily use RxJS, which has pipable operators (much better!).



          mcityService.authLogin(request, Utils.prepareHeaders())
          .concatMap(response ->
          final Map<String, String> headers = Utils.prepareHeaders(resp.tokenType,resp.accessToken);
          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> ResponseUserDetails.of(response, userDetails));
          )
          .doOnNext(responseDetails ->
          // Hanlde ResponseUserDetails object
          )
          .doOnError(throwable ->
                     // Handle exception
          final String message = throwable.getMessage();
          ...
                 )
          .subscribe(
          responseDetails -> ... ,
          throwable -> ...
          );



          If you don't want to use an additional class, you can create an Object on the fly



          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> new Object()
          public Response r = response;
          public UserDetails ud = userDetails;
          );


          And access its fields via



          .doOnNext(responseDetails -> 
          final Response r = responseDetails.r;
          final UserDetails ud = responseDetails.ud;
          ...
          )



          static class ResponseUserDetails 
          final Response response;
          final UserDetails userDetails;

          ResponseUserDetails(
          final Response response,
          final UserDetails userDetails)
          this.response = response;
          this.userDetails = userDetails;


          static ResponseUserDetails of(
          final Response response,
          final UserDetails userDetails)
          return new ResponseUserDetails(response, userDetails);





          enter image description here






          share|improve this answer















          Yes, you can, and should use flatMap / concatMap / switchMap.

          Also, sorry if it is not coded well, I primarily use RxJS, which has pipable operators (much better!).



          mcityService.authLogin(request, Utils.prepareHeaders())
          .concatMap(response ->
          final Map<String, String> headers = Utils.prepareHeaders(resp.tokenType,resp.accessToken);
          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> ResponseUserDetails.of(response, userDetails));
          )
          .doOnNext(responseDetails ->
          // Hanlde ResponseUserDetails object
          )
          .doOnError(throwable ->
                     // Handle exception
          final String message = throwable.getMessage();
          ...
                 )
          .subscribe(
          responseDetails -> ... ,
          throwable -> ...
          );



          If you don't want to use an additional class, you can create an Object on the fly



          return mcityService.getUserDetails(selectedCity.id, headers)
          .map(userDetails -> new Object()
          public Response r = response;
          public UserDetails ud = userDetails;
          );


          And access its fields via



          .doOnNext(responseDetails -> 
          final Response r = responseDetails.r;
          final UserDetails ud = responseDetails.ud;
          ...
          )



          static class ResponseUserDetails 
          final Response response;
          final UserDetails userDetails;

          ResponseUserDetails(
          final Response response,
          final UserDetails userDetails)
          this.response = response;
          this.userDetails = userDetails;


          static ResponseUserDetails of(
          final Response response,
          final UserDetails userDetails)
          return new ResponseUserDetails(response, userDetails);





          enter image description here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 11:56

























          answered Mar 22 at 10:47









          LppEddLppEdd

          10k31749




          10k31749












          • Comments are not for extended discussion; this conversation has been moved to chat.

            – Jean-François Fabre
            Mar 22 at 20:59

















          • Comments are not for extended discussion; this conversation has been moved to chat.

            – Jean-François Fabre
            Mar 22 at 20:59
















          Comments are not for extended discussion; this conversation has been moved to chat.

          – Jean-François Fabre
          Mar 22 at 20:59





          Comments are not for extended discussion; this conversation has been moved to chat.

          – Jean-François Fabre
          Mar 22 at 20:59



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55297223%2frxjava-chain-observables%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해