如何使用RXJS动态链接函数调用?

时间:2016-04-19 20:06:52

标签: javascript typescript promise rxjs rxjs5

我需要在第一次调用时缓存请求的结果,然后读取后续调用的缓存值。

为了达到这个目标,我正在使用承诺而我正在将它们链接起来。我有一个有效的解决方案,但我希望将其转换为RxJS的可观察量,而不是Promises。

这是我的工作解决方案:

private currentPromise: Promise<{ [key: string]: any }>;
private cache: any;
public getSomething(name: string): Promise<number>{
  return this.currentPromise = !this.currentPromise ? 
    this._getSomething(name) : 
    new Promise((r) => this.currentPromise.then(() => this._getSomething(name).then((res) => r(res))));
}

private _getSomething(name: string): Promise<any> {
  return new Promise((resolve) => {
    if (this.cache[name]) {
      this.messages.push("Resolved from cache");
        resolve(this.cache[name]);
      } else {
        // Fake http call. I would use Angular's Http class.
        setTimeout(()=> {this.messages.push("Resolved from server"); this.cache[name] = name; resolve(this.cache[name]); }, 2000 );
      }
  });
}

this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));

你可以在这个plunkr上测试它:https://plnkr.co/edit/j1pm2GeQf6oZwRvbUsXJ?p=preview

如何使用RxJS 5 beta实现相同的目标?

更新

根据Bergi的评论,我更新了我的plunkr和我的代码,使其更接近我的真实案例

1 个答案:

答案 0 :(得分:1)

AsyncSubjects是Promise的Rx类似物。 publishLast是将可观察量转化为一个的最佳方式。这样的事情应该有效:

$sql2 = "SELECT
            fc.cat_id,
            fc.cat_title,
            f.forum_name,
            COUNT(f.forum_id) as count
        FROM forums as f
        LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id)
        GROUP BY f.cat_id";

$result2 = query($sql2);

while (($row = mysqli_fetch_assoc($result)) != false) {

    $cat_id = $row['cat_id']; // category id
    $cat_title = $row['cat_title']; // category title
    $forum_name = $row['forum_name']; // forum name
    $count = $row['count']; // count of forum_id (grouped by cat_id)

    echo "<tr>";
    echo "<td>$cat_id</td>";
    echo "<td><a href='viewforum.php?f={$cat_id}'>$cat_title</a><br>$forum_name admin</td>";
    echo "<td>$count</td>";
    echo "<td>0</td>";
    echo "</tr>";

}