Reputation: 1736
Im iterating over an array of objects and for each iteration i run a observable.subscribe, how can i ensure that the all the subscribes were completed, so i can call another function?
this is the function
calculaSimulacoesPorInscricao(){
let lista = ["2019-01-01","2020-02-02","2021-01-01","2022-01-01","2023-01-01"];
this.cliente.coberturas.forEach(cobertura => {
cobertura.MovimentosProjetados = [];
this._dataService.ObterSimulacao(cobertura.codigoInscricao,lista)
.subscribe((data:any[])=>{
data[0].simulacaoRentabilidadeEntities.forEach(simulacao =>{
let movimento = {
dataMovimento: '',
valor: 1,
imposto: 1,
percentualCarregamento: 1,
fundoCotacao: []
};
movimento.dataMovimento = simulacao.anoRentabilidade;
movimento.imposto = cobertura.totalFundos * simulacao.demonstrativo.demonstrativo[0].aliquota;
movimento.percentualCarregamento = simulacao.valorPercentualCarregamento * (cobertura.totalFundos + (cobertura.totalFundos * simulacao.percentualRentabilidade));
movimento.valor = cobertura.totalFundos + (cobertura.totalFundos * simulacao.percentualRentabilidade);
cobertura.MovimentosProjetados.push(movimento);
});
})
});
this.calcularSimulacao();
}
i need to call calcularSimulacao() after all subscribe inside the coberturas.foreach is done. Any tips?
Upvotes: 2
Views: 9077
Reputation: 3636
You can try using forkJoin
with onCompleted
callback. See below:
calculaSimulacoesPorInscricao() {
let lista = [
'2019-01-01',
'2020-02-02',
'2021-01-01',
'2022-01-01',
'2023-01-01'
];
let all_obs = [];
this.cliente.coberturas.forEach(cobertura => {
cobertura.MovimentosProjetados = [];
all_obs.push(
this._dataService.ObterSimulacao(cobertura.codigoInscricao, lista).pipe(
map(
(data: any[]) => {
data[0].simulacaoRentabilidadeEntities.forEach(simulacao => {
let movimento = {
dataMovimento: '',
valor: 1,
imposto: 1,
percentualCarregamento: 1,
fundoCotacao: []
};
movimento.dataMovimento = simulacao.anoRentabilidade;
movimento.imposto =
cobertura.totalFundos *
simulacao.demonstrativo.demonstrativo[0].aliquota;
movimento.percentualCarregamento =
simulacao.valorPercentualCarregamento *
(cobertura.totalFundos +
cobertura.totalFundos * simulacao.percentualRentabilidade);
movimento.valor =
cobertura.totalFundos +
cobertura.totalFundos * simulacao.percentualRentabilidade;
cobertura.MovimentosProjetados.push(movimento);
});
})
)
);
});
forkJoin(all_obs).subscribe(
undefined,
undefined,
() => {
this.calcularSimulacao();
}
);
}
Just remember to import forkJoin
if you're using RxJS 6.
import { forkJoin } from 'rxjs';
Upvotes: 4
Reputation: 96969
In RxJS 5 it could look like this. In RxJS 6 just replace Observable.forkJoin
with forkJoin
.
const observables = [];
this.cliente.coberturas.forEach(cobertura => {
// just create the Observable here but don't subscribe yet
observables.push(this._dataService.ObterSimulacao(...));
});
Observable.forkJoin(observables)
.subscribe(results => this.calcularSimulacao());
Upvotes: 2