rxjs何时可观察到的订阅同步执行?

时间:2019-09-18 22:02:55

标签: angular rxjs observable

在下面的代码块中,

let ob = of(1,2,3);
ob.subscribe((v)=>{
   console.log(v)
})
console.log("end")

这些值是同步发出的。预订中的功能是否一定要在打印end之前执行?  所以输出将始终是。

1
2
3
end

3 个答案:

答案 0 :(得分:2)

如果您的可观察流仅运行同步代码,是的,就像同步运行正常的函数执行一样,但是,如果异步,它将异步运行,而promise将始终异步运行

代码的异步版本类似于

new PaymentDefinition()
                   {
                       name = "Trial Plan",
                       type = "TRIAL",
                       frequency = "DAY",
                       frequency_interval = "1",
                       amount = GetCurrency("0"),
                       cycles = "1",
                       charge_models = new List<ChargeModel>
                       {
                            new ChargeModel()
                            {
                                type = "TAX",
                                amount = GetCurrency("0")
                            },
                            shippingChargeModel
                       }
                   },


                  new PaymentDefinition
                  {
                      name = "Standard Plan",
                      type = "REGULAR",
                      frequency = "Year",
                      frequency_interval = "1",
                      amount = GetCurrency(AppUtils.YearlyAmount.ToString()),

                     cycles = "100",
                     charge_models = new List<ChargeModel>
                        {
                                new ChargeModel
                                {
                                    type = "TAX",
                                    amount = GetCurrency("0")
                                },
                                shippingChargeModel
                        }
                    },

答案 1 :(得分:1)

如果可观察对象稍后发出,则不会

const { BehaviorSubject } = rxjs;

let bs$ = new BehaviorSubject(1);

setTimeout(() => { bs$.next(2); }, 500);
setTimeout(() => { bs$.next(3); }, 1000);

bs$.subscribe(v => {
   console.log(v)
});

console.log('end');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>

答案 2 :(得分:0)

可观察值是Stream of Data而不是async functions。同步运行,并且取决于osbervable内部的逻辑,它会一次或多次(如操作符a)同步调用next方法,或者像在SetTimeout函数内部调用next方法一样异步调用。