修改以澄清我想要实现的目标。
我可以用RxJ编写代码,其中 Observable 从 Observers 收集数据吗?如下方案:
.filter()
)都会回答使用 Rxjs ,当Observable使用.next()
触发新值时,每个带有方法.subscribe()
的观察者都会对此作出反应,但我不知道这是怎么回事observer可以向Observable返回一个值。
所以,这就是我需要的:
我希望现在我清楚我的需求:)。
答案 0 :(得分:2)
好的,我更了解这个问题。
我相信你需要的是审查员和学生都有Observable和Observer属性。这是使用Observables进行双向通信的唯一方法,因为它们只是一种单向通信机制。
race
让他们参加比赛。const question$ = Rx.Observable.range(1, 4)
// in case you want everyone to wait
.publish();
function makeStudent(name, worstTimeToAnswer) {
return q =>
Rx.Observable.of(`${name} answers question ${q}`)
.delay(Math.random() * 1000 * worstTimeToAnswer);
}
// Alice answers questions in at most 5 seconds
const alice = makeStudent("Alice", 5);
// Bob answers questions in at most 7 seconds
const bob = makeStudent("Bob", 7);
// This stream contains one answer for each question, as long as someone
// answered fast enough.
const winningAnswer$ =
question$
.concatMap(q =>
// see who answers faster between Alice and Bob
Rx.Observable.race(alice(q), bob(q))
// or drop the question if nobody answers within 4 seconds
.takeUntil(Rx.Observable.timer(4000))
);
winningAnswer$.subscribe(a => console.log(a));
question$.connect(); // questions start flowing
// should print something like:
// Alice answers question 1
// Bob answers question 3
// Alice answers question 4
// where Q2 was dropped because nobody answered fast enough
// and Alice often answers faster than Bob
如果您确实需要一个反馈循环,其中问题的答案会改变下一个问题,那么您可能需要使用Subject
来关闭循环。
答案 1 :(得分:1)
Events-ex库支持观察者将值发送回observable。
eventable = require('events-ex/eventable')
class Examiner
# advanced usage see API topic.
eventable Examiner
makeQuestion: ->
aQuestion = '....'
theAnswer = this.emit 'ask', aQuestion
class Student
constructor: (aExaminer)->
aExaminer.on 'ask', this.answer if aExaminer
answer: (aQuestion)->
# this is the event object, not the student instance.
this.result = 'myAnswer'
this.stopped = true # stop other listeners. defaults to false.
return