Rx.Observable.subscribe将值返回给observable

时间:2016-08-09 22:00:58

标签: rxjs

修改以澄清我想要实现的目标。

我可以用RxJ编写代码,其中 Observable Observers 收集数据吗?如下方案:

  1. 一名考官,多名学生
  2. 审查员可观察
  3. 每个学生观察者
  4. 每次考官提出问题时,知道答案的学生(即.filter())都会回答
  5. 审查员将第一个答案作为正确答案
  6. 使用 Rxjs ,当Observable使用.next()触发新值时,每个带有方法.subscribe()的观察者都会对此作出反应,但我不知道这是怎么回事observer可以向Observable返回一个值。

    所以,这就是我需要的:

    1. Observer如何将值发送回Observable?
    2. 是否有可能第一个响应的观察者赢得比赛而其他人在此之后被忽略?
    3. 是否可以知道Observer没有响应?
    4. 我希望现在我清楚我的需求:)。

2 个答案:

答案 0 :(得分:2)

好的,我更了解这个问题。

我相信你需要的是审查员和学生都有Observable和Observer属性。这是使用Observables进行双向通信的唯一方法,因为它们只是一种单向通信机制。

  1. 解决方案是让学生的答案是可观察的。
  2. 然后你可以使用race让他们参加比赛。
  3. 嗯......你必须定义一个学生不回答的意思:是否有超时,或者他们是否能够宣布他们以后不会回答?
  4. 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
相关问题