共享單個訂閱(釋出)

鑑於來自商家的 IObservable<Offer> offers 以固定價格購買或出售某種型別的商品,我們可以按照以下方式匹配成對的買家和賣家:

var sellers = offers.Where(offer => offer.IsSell).Select(offer => offer.Merchant);
var buyers = offers.Where(offer => offer.IsBuy).Select(offer => offer.Merchant);
var trades = Observable.Zip(sellers, buyers, (seller, buyer) => new Trade(seller, buyer));

這個問題是每次訂閱 trades 都會訂閱 offers 兩次。我們可以使用 Publishsellersbuyers 共享一個 offers 訂閱:

var trades = offers.Publish(_offers =>
{
    var sellers = _offers.Where(offer => offer.IsSell).Select(offer => offer.User);
    var buyers = _offers.Where(offer => offer.IsBuy).Select(offer => offer.User);
    return Observable.Zip(sellers, buyers, (seller, buyer) => new Trade(seller, buyer));
});