Performing advanced http requests in rxjs

岁酱吖の 提交于 2019-11-29 16:06:47

So you need to call the first request and wait for its response and then call the two other requests (for options and the answer) at the same time.

Since I want to know when both responses are ready I'll use Observable.forkJoin() operator that emits a single array with all values of source Observables when they completed and then add data to the qoa variable that I'll just pass to the Observer when it subscribes.

Operators such concat() or concatMap() are good to make multiple HTTP calls in order but not very useful when you need to create multiple Observable to construct one large response you want to emit (QuestionOptionsAnswer in your case).

I also used Observable.of(...) to simulate HTTP requests. I don't know what's your usecase so you'll maybe don't use Observable.create() and use Subject instead:

function getQOA() {
    return Observable.create(observer => {

        Observable.of({ question_id: '1' }).subscribe(response => {
            var qoa = new QuestionOptionsAnswer();
            let question = new Question();
            question.idQuestion = response.question_id;

            qoa.question = question;

            let obs1 = Observable.of({ answer_id: '1', answer: 'bla' });
            let obs2 = Observable.of([{ option_id: '1', option: 'ble' }]);

            Observable.forkJoin(obs1, obs2).subscribe(responses => {
                let [answerResponse, optionsResponse] = responses;

                let answer = new Answer();
                answer.idAnswer = answerResponse.answer_id;
                answer.answer = answerResponse.answer;
                qoa.answer = answer;

                qoa.options = optionsResponse.map(o => {
                    let option = new Option();
                    option.idOption = o.option_id;
                    option.option = o.option;
                    return option;
                });

                observer.next(qoa);
            });
        });
    });
}

getQOA().subscribe(qoa => console.log(qoa));

Prints to console:

QuestionOptionsAnswer {
  question: Question { idQuestion: '1' },
  answer: Answer { idAnswer: '1', answer: 'bla' },
  options: [ Option { idOption: '1', option: 'ble' } ] }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!