How can I `await` on an Rx Observable?

前端 未结 5 736
孤城傲影
孤城傲影 2020-11-28 04:39

I\'d like to be able to await on an observable, e.g.

const source = Rx.Observable.create(/* ... */)
//...
await source;

A naive attempt res

5条回答
  •  暖寄归人
    2020-11-28 05:20

    You have to pass a promise to await. Convert the observable's next event to a promise and await that.

    if (condition) {
      await observable.first().toPromise();
    }
    

    Edit note: This answer originally used .take(1) but was changed to use .first() which avoids the issue of the Promise never resolving if the stream ends before a value comes through.

提交回复
热议问题