我怎样才能在RxJS中创建Cold Subject?

时间:2016-10-09 19:01:42

标签: rxjs5

默认 RxJs主题是" ",但可以创建" "是否可以从头开始获取从中传播的所有值?

即:

let s = new Subject();
s.next(1);
s.next(2);
s.subscribe(n => console.log(n)); //to get here 1 2 3
s.next(3);

2 个答案:

答案 0 :(得分:3)

您可以使用ReplaySubject执行此操作。要记住的一件事是,ReplaySubject期望在创建期间的数字能够知道它应该缓冲多少个值。你无法缓冲所有元素。

const subject = new Rx.ReplaySubject(10);

subject.next("1");
subject.next("2");
subject.next("3");
subject.next("4");
subject.next("5");

subject.subscribe(
  (val) => console.log(val)
);    

subject.next("6");

// Logs out 
// 1
// 2
// 3
// 4
// 5
// 6

jsbin:http://jsbin.com/rocofa/edit?js,console

答案 1 :(得分:1)

class CustomExtensions: NSObject { /* Useful extensions, nothing else here */ } // Example extension extension Int { func formatAsTimeString() -> String { let seconds = self % 60 let minutes = (self / 60) % 60 let hours = self / 3600 let stringHours = hours > 9 ? String(hours) : "0" + String(hours) let stringMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes) let stringSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds) if hours > 0 { return "\(stringHours):\(stringMinutes):\(stringSeconds)" } else { return "\(stringMinutes):\(stringSeconds)" } } } // More extensions below 的行为与您描述的完全一致。有关详细信息,请参阅ReactiveX Subject docs