0

I have a little spring application that uses Spring social twitter to stream data from twitter's public API.

The code is very simple. I have a configuration class that expose a bean of type twitter template.

@Bean
Twitter getTwitterTemplate() {
    Twitter twitter = new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
    return twitter;
}

I have another service class that uses the twitter template bean to filter the stream based on some hashtags. I start the streaming process in the postContruct of the service bean.

@Autowired
Twitter twitter;

@Value("${app.hashtags}")
String[] hashtags;

@PostConstruct
private void startStream() {
    FilterStreamParameters parameters = new FilterStreamParameters();

    for (String hashtag : hashtags) {
        parameters.track(hashtag);
    }

    twitter.streamingOperations().filter(parameters, tweetStreamListeners);

}

Once the application starts, the streaming is starting and everything works fine.

My question is how to stop the streaming based on some action? Say for example the application will provide an endpoint when called it should stop the streaming process.

Fanooos
  • 2,718
  • 5
  • 31
  • 55

1 Answers1

1

The Stream interface has a close() method, so you could do something like:

...
private Stream myStream;
... 
@PostConstruct
private void startStream() {
    this.myStream = twitter.streamingOperations().filter(parameters, tweetStreamListeners);

private void closeStream() {
    this.myStream.close();
}
Andrea Nagy
  • 1,201
  • 9
  • 21
  • In which version of spring-social-twitter this method exists? – Fanooos Oct 14 '18 at 09:27
  • I am not sure when it was added, it is present in the [1.1.0.Release](https://docs.spring.io/autorepo/docs/spring-social-twitter/1.1.0.RELEASE/apidocs/org/springframework/social/twitter/api/StreamingOperations.html). If you check most methods in `streamingOperations()` e.g: `filter()` will return with a `Stream`, which can be closed. – Andrea Nagy Oct 15 '18 at 06:44
  • Thanks @Andrea. Kindly edit the answer and use Close() method instead of Stop() and I will mark it as the correct answer. – Fanooos Oct 15 '18 at 07:04
  • Updated, thanks for the response. I just noticed that I put stop() instead of close(). Sorry for the confusion! – Andrea Nagy Oct 15 '18 at 07:07