使用RxScala进行反应式编程

时间:2015-07-24 07:40:20

标签: scala system.reactive rx-java rx-scala

我有一个通过Socket协议连接到服务的Observable。与套接字的连接通过客户端库进行。我使用的客户端库有java.util.Observer,我可以注册被推入的事件

//Sentence Capitalizer
#include <iostream>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;

int main()
{
  char argument[1024];
  cout<<"Please enter a c string as an agrument and I will capitalizes the first character of each sentence in string: ";
  cin.getline(argument, 1024);
  argument[0] = toupper(argument[0]);
  int i = 0;
  while (argument[i+2] != '\0')
  {
      if (argument[i] == '.')
      {
          argument[i+2] = toupper(argument[i+2]); 
      }
      i++;
  }
  cout<<argument[0]<<endl;
      return 0;
}

我有两个我不明白的未解决的问题。

如何在订阅者中获得Step:3的结果?

每当我获得MyEvent时,如下所示的订阅者,我发现正在创建一个新连接。最后,为每个传入的事件运行步骤1,步骤2和步骤3.

final class MyObservable extends Observable[MyEvent] {

  def subscribe(subscriber: Subscriber[MyEvent]) = {
    // connect to the Socket (Step: 1)
    // get the responses that are pushed (Step: 2)
    // transform them into MyEvent type (Step: 3)
  }
}

1 个答案:

答案 0 :(得分:2)

除非我误解了您的问题,否则请致电onNext

def subscribe(subscriber: Subscriber[MyEvent]) = {
  // connect to the Socket (Step: 1)
  // get the responses that are pushed (Step: 2)
  // transform them into MyEvent type (Step: 3)

  // finally notify the subscriber:
  subscriber.onNext(myEventFromStep3)
}

订阅的代码会执行以下操作:

myObservable.subscribe(onNext = println(_))