3

RxJについていくつか理解しようとしています。私がやりたいことは、いくつかの JSON データを消費し、そのデータが入ってくるとすぐに DOM でそのデータのレンダリングを開始することです。ストリームの要求、応答、および表示をセットアップしました。それはすべてうまく出力していますが、時間の経過ではなく、一度にすべて実行しています。

ファイル全体が完了するのを待ってから一度に表示すると、長い待ち時間が発生するのではなく、ページにデータが入ってくると表示を開始したいと考えています。

//Cache the selector
var $resultList = $('.results');

//Gets the JSON (this will not be a static file,just for testing)
var requestStream = Rx.Observable.just("/results.json");

var responseStream = requestStream
    .flatMap(function(requestUrl) {
            return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl))
             });

var displayStream = responseStream.subscribe(
    function(response) {
    //This maps to a Handlebars Template and puts it on the DOM
    $resultList.html(compiledTemplate(response)); 
            },
            function(err) {
                    console.log('Error: %s', err);
             },
             function() {
                    console.log('Completed');
             });




//Sample of the data from the JSON file
Object{
    beginIndex: "1"
    catId: "111"
    endIndex: "1"
    products: Array[100]

}
4

1 に答える 1

5

よく理解できれば、次の 2 つの関連するポイントがあります。

  1. そのファイルの読み取りが終了したときに、1 つの大きなオブジェクトではなく、そのファイルからオブジェクトのストリームを取得する方法を見つける必要があります ( I want to start showing the data on the page as its coming in)。そのメカニズムは、Rxjs (すべての行が情報表示などにつながる可能性のあるオブジェクトですか?) よりも、ソースの構造 (ファイルおよびファイル読み取りメカニズム) に最初に依存します。「表示可能な情報の最小単位」を取得したら、必要に応じて Rxjs を使用してそれをバッファリング/処理できます (オブジェクトごと、または 100 オブジェクトごとに何かを表示したり、不要な属性などを削除したりしますか?)
  2. 新しいデータが到着するたびに、表示を段階的に更新する必要があります。つまり 、コンパイルされた新しいものを古いもの$resultList.html($resultList.html() + compiledTemplate(response)); に追加するようなものが必要です。html

UPDATE:配列をチャンクするために、このjsfiddleを見ることができます:http://jsfiddle.net/429vw0za/

var ta_result = document.getElementById('ta_result');

function emits ( who, who_ ) {return function ( x ) {
 who.innerHTML = [who.innerHTML, who_ + " emits " + JSON.stringify(x)].join("\n");
};}

function fillArrayWithNumbers(n) {
        var arr = Array.apply(null, Array(n));
        return arr.map(function (x, i) { return {prop1: i, prop2:i, prop3:i} });
    }

var sampleObj = {
    beginIndex: "1",
    catId: "111",
    endIndex: "1",
    products: fillArrayWithNumbers(100)
}

console.log('sampleObj', sampleObj);

var result$ = Rx.Observable
  .from(sampleObj.products)
  .bufferWithCount(10)
  .map(function(mini_array){return {
  beginIndex: sampleObj.beginIndex,
  catId: sampleObj.catId,
  endIndex: sampleObj.endIndex,
  products: mini_array
  }})
  .do(emits(ta_result, 'result'));

result$.subscribe(function(){    });

サイズ 100 の配列から取得したサイズ 10 の配列を持つオブジェクトのストリームが得られます。

于 2015-12-19T18:05:27.593 に答える