0

I have a function that returns something like Observable<[number, Array<DataItem>]>. Is it possible to write some function that returns Observable<[number, Array<PageWithDataItems>] using some Observable functions, given a function chunk (chunks the DataItem array according to page size) and a simple constructor that creates a PageWithDataItems with a chunked DataItem array. What I have is some code that subscribes to Observable<[number, Array<DataItem>]> and then creates a new Observable, but I am hoping it would be possible to do the same with map, mapTo, switchMap or similar. I am a bit lost in all the Observable functions, so any help?

Lars Nielsen
  • 365
  • 1
  • 2
  • 14

1 Answers1

1

I am not entirely sure what you are going for here, but I gave it a shot:

// stream would be your data... just random chunks of numbers as an example here.
const stream = Rx.Observable.range(0, 480).bufferWithCount(100).select(d => [Math.random() * 100, d]);

class DataChunk<T> {
    constructor(public data: Array<T>) { }
}

const pageSize = 10;

stream
    // I do not understand what the 'number' in your [number, Array<DataItem>]
    // represents. But it is the 'someNumber' item here.. 
    .map(d => ({someNumber: <number>d[0], data: <number[]>d[1]}))
    .map(d => ({
        someNumber: d.someNumber,
        pages: Ix.Enumerable
            .fromArray(d.data)
            .select((item, idx) => ({ pageNr : idx % pageSize, item: item }))
            .groupBy(i => i.pageNr)
            .select(pageItems => new DataChunk(pageItems.select(i => i.item).toArray()))
            .toArray() 
    }))
    .subscribe(dataInfo => {
        // here each dataInfo sent down the stream will have been split up in to chunks
        // of pageSize
        log('Data recieved: ');
        log('  someNumber: ' + dataInfo.someNumber);
        log('  page count: ' + dataInfo.pages.length);
    });

Working example on jsfiddle.

I used IxJS to do the chunking. It works similarly to RxJS but operates on collections (e.g. arrays) and not streams of evens like RxJS. I hope this was close to what you wanted, your question is not entirely clear.

Nypan
  • 6,980
  • 3
  • 21
  • 28