Subscribe to a stream with RxJS and twitter-stream-api module

我们两清 提交于 2019-12-01 11:38:40

RxJS 5 doesn't have any methods to convert stream from/to an Observable so you'll need to do this by yourself. Ideally with Observable.create.

const Rx = require('rxjs');
const Observable = Rx.Observable;

var TwitterStream = require('twitter-stream-api'),

...

var source$ = Observable.create(observer => {
  var Twitter = new TwitterStream(keys);
  Twitter.stream('statuses/filter', {
    track: filter
  });

  Twitter.on('data', function (obj) {
    observer.next(obj);
  });

  return () => {
    Twitter.close();
  };
});

This makes a cold Observable that'll connect to Twitter only when you subscribe to it. The Observable.create static methods let's you push values to the observer and at the end return a tear down function then just closes the connection. This function is called when you unsubscribe or when the Observable completes.

Then you can chain this Observable with whatever you want:

source$.filter(...).map(...)

Note, that there're also methods Observable.bindCallback() and Observable.bindNodeCallback() but these wouldn't help you much in your situation.

Read more:

Here's an example using desmondmorris/node-twitter and rxjs 5.

const Observable = require('rxjs').Observable;

Observable
  .of(new require('twitter')({
    consumer_key: 'xxxx',
    consumer_secret: 'xxxx',
    access_token_key: 'xxxx',
    access_token_secret: 'xxxx',
  })).mergeMap(twitter =>
    Observable
    .fromEvent(twitter.stream('statuses/filter', {
        track: 'Stack Overflow'
      }),
      'data'))
  .filter(tweet => tweet.user.follow_count > 10000)
  .subscribe(console.log);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!