简体   繁体   中英

How to create an Observable that depends on another Observable in RxJS

I have a cart service that provides reactive data about the cart:

export interface OrderItem {
  product: IProduct
  quantity: number
}

private subject = new BehaviorSubject<OrderItem[]>([])
private orderItems: Observable<OrderItem[]> = this.subject.asObservable()

getItems(): Observable<OrderItem[]> {
    return this.orderItems
  }

I want to create a method that will return an Observable of the number of products in the cart, like this (pseudo-code):

return getItems().subscribe(items => {
  let cartSize = 0
  items.forEach(item => cartSize += item.quantity)
})

So basically to return cartSize as an observable, how can i do that?

This is not an observable depending on another observable (which would call for operators like for example mergeMap, switchMap and withLatestFrom), but it is merely a transformation of your observable. This would be a map.

For example:

const totalQuantity$ = getItems().pipe(
  map(items => {
    // this would be nicer using a reduce but ok
    let cartSize = 0
    items.forEach(item => cartSize += item.quantity)
    return cartSize
   })
 )

And then subscribe to totalQuantity$ somewhere.

Not related, but you can remove this orderItems property, and refactor the getItems method to:

getItems(): Observable<OrderItem[]> {
  return this.subject.asObservable()
}

Anyways, if you use some pipe operators in this method, than you simply can work on this.subject , because all of pipes returns Observable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM