问题
Today I finally stumbled upon the solution of a really trivial RX problem: Suppose you have an Observable which returns Lists of items. Like
Observable<List<String>>
. You often receive something like this as responses from web APIs.
However chances are you want to operate on the single items, in this case the Strings.
flatMapIterable
to the rescue! This handy operator flattens a stream ofIterables
into a stream generated from the single items of theseIterables
by means of a mapping function.
RxJava: flattening a stream of Iterables | by Sven Bendel
I'm writing in .NET Core if that matters.
Example in RxJava: Convert Observable<List<Car>> to a sequence of Observable<Car> in RxJava
回答1:
The LINQ operation to map a collection-of-collection-of-items into an aggregated collection of items is SelectMany
. This operation exists in System.Reactive as well, allowing you to create a single Observable from a collection of Observables:
http://www.introtorx.com/content/v1.0.10621.0/08_Transformation.html#SelectMany
Observable.Range(1,3)
.SelectMany(i => Observable.Range(1, i))
.Dump("SelectMany");
...we will now get an output with the result of each sequence ([1], [1,2] and [1,2,3]) flattened to produce [1,1,2,1,2,3].
SelectMany-->1
SelectMany-->1
SelectMany-->2
SelectMany-->1
SelectMany-->2
SelectMany-->3
SelectMany completed
回答2:
It really is trivial to to do this in C#. Just do this:
IObservable<IList<int>> source =
Observable.Return(new [] { 1, 2, 3 }.ToList());
IObservable<int> output =
from list in source
from item in list
select item;
Simple.
回答3:
Edit: My mistake, it's also SelectMany as an overloaded method:
public IObservable<string> IterateObservable(IList<string> strings)
{
return strings
.ToObservable()
.Buffer(100) // IObservable<IList<string>>
.SelectMany(item => item); // IObservable<string>
}
It appears there is no equivalent to flatMapInterable in Rx.NET so you must stick with combining SelectMany and ToObservable. Plus more to actually apply a transformation to each item.
Example (same as the RxJava example in the stackoverflow link):
public IObservable<string> IterateObservable(IList<string> strings)
{
return strings
.ToObservable()
.Buffer(100)
.SelectMany(list => list.ToObservable());
}
To perform an operation on it similar to flatMapIterable (but more verbose of course):
public IObservable<string> IterateObservable(IList<string> strings)
{
return strings
.ToObservable()
.Buffer(100)
.SelectMany(
list => list.ToObservable()
.Select( stringInList => stringInList.Trim()));
}
来源:https://stackoverflow.com/questions/48994890/whats-the-rx-net-equivalent-to-flatmapiterable