Merge two observables, single output











up vote
0
down vote

favorite












Hello guys Im trying to grasp RxJS lib and the whole idea of reactive programming.
Im trying to merge two observables into one. First observable contains array of objects DefectImages the second observable contains array of strings, which then I convert to array of DefectImages. After that I would like to merge these two observables into one.



Below my code:



const observable = CachedPhotosBuffer.getInstance().asObservable()
.pipe(
switchMap(data => {
return data.map((url) => DefectImage.createTempImage(url, 'you', Date.now()));
})
);
this.observable = Observable.create(observer => observer.next(this.defectImages));
this.observable.pipe(
merge(observable)
).subscribe(data => console.log('merge', data))


This KIND OF works as I expect BUT this merged observables Is connected to html angular template.



<ion-list>
**<ng-container *ngFor="let image of observable | async">**
<ion-item *ngIf="image.deletedAt === undefined">
<span class="item-container" (click)="showImage(image)">
<ion-thumbnail item-start>
<img id="{{image.url}}" src="{{getUrl(image) + image.url}}">
</ion-thumbnail>
<span>
<p>created at: {{image.createdAt | date: 'd/M/yy H:m'}}</p>
<p>created by: {{image.createdBy}}</p>
</span>
</span>
<button ion-button item-end (click)="removeImage(image)">
<ion-icon name="trash"></ion-icon>
</button>
</ion-item>
</ng-container>
</ion-list>


This is the console logs Im getting
enter image description here



My question is Why do I have two separate logs for each stream instead of One console log with all the data combined?










share|improve this question


























    up vote
    0
    down vote

    favorite












    Hello guys Im trying to grasp RxJS lib and the whole idea of reactive programming.
    Im trying to merge two observables into one. First observable contains array of objects DefectImages the second observable contains array of strings, which then I convert to array of DefectImages. After that I would like to merge these two observables into one.



    Below my code:



    const observable = CachedPhotosBuffer.getInstance().asObservable()
    .pipe(
    switchMap(data => {
    return data.map((url) => DefectImage.createTempImage(url, 'you', Date.now()));
    })
    );
    this.observable = Observable.create(observer => observer.next(this.defectImages));
    this.observable.pipe(
    merge(observable)
    ).subscribe(data => console.log('merge', data))


    This KIND OF works as I expect BUT this merged observables Is connected to html angular template.



    <ion-list>
    **<ng-container *ngFor="let image of observable | async">**
    <ion-item *ngIf="image.deletedAt === undefined">
    <span class="item-container" (click)="showImage(image)">
    <ion-thumbnail item-start>
    <img id="{{image.url}}" src="{{getUrl(image) + image.url}}">
    </ion-thumbnail>
    <span>
    <p>created at: {{image.createdAt | date: 'd/M/yy H:m'}}</p>
    <p>created by: {{image.createdBy}}</p>
    </span>
    </span>
    <button ion-button item-end (click)="removeImage(image)">
    <ion-icon name="trash"></ion-icon>
    </button>
    </ion-item>
    </ng-container>
    </ion-list>


    This is the console logs Im getting
    enter image description here



    My question is Why do I have two separate logs for each stream instead of One console log with all the data combined?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Hello guys Im trying to grasp RxJS lib and the whole idea of reactive programming.
      Im trying to merge two observables into one. First observable contains array of objects DefectImages the second observable contains array of strings, which then I convert to array of DefectImages. After that I would like to merge these two observables into one.



      Below my code:



      const observable = CachedPhotosBuffer.getInstance().asObservable()
      .pipe(
      switchMap(data => {
      return data.map((url) => DefectImage.createTempImage(url, 'you', Date.now()));
      })
      );
      this.observable = Observable.create(observer => observer.next(this.defectImages));
      this.observable.pipe(
      merge(observable)
      ).subscribe(data => console.log('merge', data))


      This KIND OF works as I expect BUT this merged observables Is connected to html angular template.



      <ion-list>
      **<ng-container *ngFor="let image of observable | async">**
      <ion-item *ngIf="image.deletedAt === undefined">
      <span class="item-container" (click)="showImage(image)">
      <ion-thumbnail item-start>
      <img id="{{image.url}}" src="{{getUrl(image) + image.url}}">
      </ion-thumbnail>
      <span>
      <p>created at: {{image.createdAt | date: 'd/M/yy H:m'}}</p>
      <p>created by: {{image.createdBy}}</p>
      </span>
      </span>
      <button ion-button item-end (click)="removeImage(image)">
      <ion-icon name="trash"></ion-icon>
      </button>
      </ion-item>
      </ng-container>
      </ion-list>


      This is the console logs Im getting
      enter image description here



      My question is Why do I have two separate logs for each stream instead of One console log with all the data combined?










      share|improve this question













      Hello guys Im trying to grasp RxJS lib and the whole idea of reactive programming.
      Im trying to merge two observables into one. First observable contains array of objects DefectImages the second observable contains array of strings, which then I convert to array of DefectImages. After that I would like to merge these two observables into one.



      Below my code:



      const observable = CachedPhotosBuffer.getInstance().asObservable()
      .pipe(
      switchMap(data => {
      return data.map((url) => DefectImage.createTempImage(url, 'you', Date.now()));
      })
      );
      this.observable = Observable.create(observer => observer.next(this.defectImages));
      this.observable.pipe(
      merge(observable)
      ).subscribe(data => console.log('merge', data))


      This KIND OF works as I expect BUT this merged observables Is connected to html angular template.



      <ion-list>
      **<ng-container *ngFor="let image of observable | async">**
      <ion-item *ngIf="image.deletedAt === undefined">
      <span class="item-container" (click)="showImage(image)">
      <ion-thumbnail item-start>
      <img id="{{image.url}}" src="{{getUrl(image) + image.url}}">
      </ion-thumbnail>
      <span>
      <p>created at: {{image.createdAt | date: 'd/M/yy H:m'}}</p>
      <p>created by: {{image.createdBy}}</p>
      </span>
      </span>
      <button ion-button item-end (click)="removeImage(image)">
      <ion-icon name="trash"></ion-icon>
      </button>
      </ion-item>
      </ng-container>
      </ion-list>


      This is the console logs Im getting
      enter image description here



      My question is Why do I have two separate logs for each stream instead of One console log with all the data combined?







      javascript angular rxjs reactive-programming






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 at 19:15









      filemonczyk

      342319




      342319
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:



          zip(observable, this.observable)
          .pipe(map(x => x[0].concat(x[1])))
          .subscribe(data => console.log('merge', data))


          More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.



          And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.






          share|improve this answer























          • works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
            – filemonczyk
            Nov 21 at 19:58












          • I edited the answer.
            – Rolvernew
            Nov 21 at 20:16











          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',
          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%2f53419090%2fmerge-two-observables-single-output%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








          up vote
          1
          down vote



          accepted










          Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:



          zip(observable, this.observable)
          .pipe(map(x => x[0].concat(x[1])))
          .subscribe(data => console.log('merge', data))


          More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.



          And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.






          share|improve this answer























          • works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
            – filemonczyk
            Nov 21 at 19:58












          • I edited the answer.
            – Rolvernew
            Nov 21 at 20:16















          up vote
          1
          down vote



          accepted










          Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:



          zip(observable, this.observable)
          .pipe(map(x => x[0].concat(x[1])))
          .subscribe(data => console.log('merge', data))


          More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.



          And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.






          share|improve this answer























          • works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
            – filemonczyk
            Nov 21 at 19:58












          • I edited the answer.
            – Rolvernew
            Nov 21 at 20:16













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:



          zip(observable, this.observable)
          .pipe(map(x => x[0].concat(x[1])))
          .subscribe(data => console.log('merge', data))


          More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.



          And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.






          share|improve this answer














          Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:



          zip(observable, this.observable)
          .pipe(map(x => x[0].concat(x[1])))
          .subscribe(data => console.log('merge', data))


          More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.



          And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 20:20

























          answered Nov 21 at 19:31









          Rolvernew

          1817




          1817












          • works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
            – filemonczyk
            Nov 21 at 19:58












          • I edited the answer.
            – Rolvernew
            Nov 21 at 20:16


















          • works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
            – filemonczyk
            Nov 21 at 19:58












          • I edited the answer.
            – Rolvernew
            Nov 21 at 20:16
















          works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
          – filemonczyk
          Nov 21 at 19:58






          works like a charm, Could you explain why we need map operator? what we have before map and after map ? and why is this implemented in such way x[0].concat(x[1])??
          – filemonczyk
          Nov 21 at 19:58














          I edited the answer.
          – Rolvernew
          Nov 21 at 20:16




          I edited the answer.
          – Rolvernew
          Nov 21 at 20:16


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53419090%2fmerge-two-observables-single-output%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

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)