我希望能够解释传入的字符并“拆分”它们(在这种情况下,通过空格字符)。
var incomingCharacters = "This is a test".ToCharArray().ToObservable();
// Yields a sequence of words - "This", "is", "a", "test"
var incomingWords = incomingCharacters.Split(' ');
我做了一个操作员来做这个,但我想知道是否有更好的方法?
public static IObservable<string> Split(this IObservable<char> incomingCharacters, char s)
{
var wordSeq = Observable.Create<string>(observer =>
{
// Create an inner sequence to look for word separators; publish each word to the
// "outer sequence" as it is found
var innerSeq = incomingCharacters
.Concat(Observable.Return(s)) // Enables the last word to be processed
.Scan(new StringBuilder(), (builder, c) =>
{
if (c != s)
{
builder.Append(c);
return builder;
}
// We encountered a "split" character; publish the current completed word
// and begin collecting a new one
observer.OnNext(builder.ToString());
return new StringBuilder();
});
innerSeq.Subscribe(list => { });
return Disposable.Empty;
});
// Return the outer sequence
return wordSeq;
}