lundi 4 novembre 2019

How to call multiple subject.next() that depend on each other one after another? [RxJS]

I have a modal dialog service.
Each instance of a dialog has afterClose Subject to which this API user can subscribe in order to do something after dialog got closed.
Now I would like to add beforeClose subject, but I am not sure how to chain/compose it into the stream of my Observables.

Closing the dialog is also asynchronous.

This is more or less how it looks like:

const asyncSimulation = val =>
  new Promise(resolve => resolve(val));

class DialogService {
  dialogs = [];

  open(text) {
    const afterClose = new rxjs.Subject();
    const onClose = new rxjs.Subject();
    const beforeClose = new rxjs.Subject();

    let dialog = new ModalDialog(text, onClose, afterClose, beforeClose);
    this.dialogs.push(dialog);

    onClose.subscribe(result => {
      this.remove(dialog).subscribe(() => {
        console.log("Closed " + result);
        afterClose.next(result);
        afterClose.complete();
      })
    })

   return dialog;
  }
  
  remove(dialog) {
    return rxjs.of(1)
  }
}

class ModalDialog {
constructor(text, onClose, afterClose, beforeClose) {
  this.text = text;
  this.afterClose = afterClose;
  this.beforeClose = beforeClose;

  //private:
  this.onClose = onClose;
}

close(result) {
  this.onClose.next(result);
}

}

let dialogService = new DialogService();

let firstModal = dialogService.open("Modal 1");
let secondModal = dialogService.open("Modal 2");

secondModal.afterClose.subscribe((result) => console.log("After Close " + result));
secondModal.beforeClose.subscribe((result) => console.log("Before Close " + result));

firstModal.close("Modal 1");
secondModal.close("Modal 2");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.js"></script>

I've read already on SO that calling subscribe inside of subscribe is a bad practice, but I am not sure how write a proper stream that:

Calls next functions of my Observables in this order: onClose beforeClose remove afterClose

Should I return observable from beforeClose.next() and subscribe to it?
It does not feel right...

How about something like this?

  onClose.pipe(mergeMap(() => {
            return beforeClose
        })).subscribe((result => {
         this.remove(dialog).subscribe(() => {
            console.log("Closed " + result);
            afterClose.next(result);
            afterClose.complete();
  })
})

Aucun commentaire:

Enregistrer un commentaire