Search code examples
javaspringtwitterspring-social-twitter

spring social twitter stop streaming operation


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.


Solution

  • 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();
    }