简体   繁体   中英

c# reactive extensions from IEnumerable<IObservable<string>> to IObservable<string>

I would like to use reactive extensions to write an extension method

public static IObservable<string> ToString(
  this IEnumerable<IObservable<string>> collection,
  string start,
  string separator,
  string stop)
  {

  }

which produces a stream of strings reflecting the most up to date content of the collection of streams passed as argument. I additionally provide a start string, a separator and a stop string for formatting purposes.

When all observables have fired at least once, I want to keep track of the string representation as the different observables fire updates.

For example, assuming that start is "{", separator is ";", and stop is "}", that there are 3 observables in the collection which have all first fired "0", I want "{0;0;0}" to be the initial string that is produced by the resulting observable.

Assuming now that the first observable of the collection pushes "1", I want the next string to be produced to be "{1;0;0}" and so on.

Thanks for your answers already.

What you describe here is very similar to CombineLatest . Try the following:

public static IObservable<string> ToString(this IEnumerable<IObservable<string>> observables, string start, string separator, string stop)
{
    return observables.CombineLatest()
                      .Select(values =>
                      {
                          var sb = new StringBuilder(start);
                          var first = true;

                          foreach (var value in values)
                          {
                              if (first)
                                  first = false;
                              else
                                  sb.Append(separator);

                              sb.Append(value);
                          }

                          sb.Append(stop);
                          return sb.ToString();
                      });
}

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