Switch
幾乎總是關鍵:
var letters = new Subject<string>();
var numbers = new Subject<string>();
var predicate = lettersPublished.Select(s => s.All(c => char.IsLower(c)));
var numbersCached = numbers.Replay().RefCount();
var dummySubscription = numbersCached.Subscribe();
var combined = lettersPublished.Merge(numbersCached);
var switchFlag = predicate.Where(b => b).Take(1);
var result = switchFlag.StartWith(false).Select(b => b ? combined : letters).Switch();
var resultWithDisposal = Observable.Using(() => dummySubscription, _ => result);
建設兩個觀測,一個前謂詞是真實的(letters
你的情況),以及一(combined
),然後使用他們之間可以觀察到切換(switchflag
)。需要dummySubscription
才能讓Replay
在後一訂閱之前緩存所有值。 Using
用於轉儲dummySubscription
。
你也可以做到這一切在一個單一的表達式(給出letters
和numbers
)如下:
var oneLiner = letters.Publish(_letters => numbers.Replay(_numbers =>
_letters
.Select(s => s.All(c => char.IsLower(c)))
.Where(b => b)
.Take(1)
.StartWith(false)
.Select(b => b ? _letters.Merge(_numbers) : letters)
.Switch()
));
交換機是我錯過了什麼。謝謝! – user37078