neckobik neckobik - 1 year ago 66
Scala Question

How can I share Array from one Controller to another

I'm new to scala. What am I doing is trying to make twitter bot that collects posts from Reddit and post them to Twitter. I have to Controllers and I need to pass an array with marked reddit posts, that user want to tweet, From one controller to another. I've tried to use Singleton and Cache but, i don't know why, it's not working for me


var pickedToTwitter : List[RedditJsonData] = _
def pickedRedditsPost = Action { implicit request =>

formWithError => {
formWithError.errors.foreach(er => Logger.debug(er.message))
goodOne => {
sessionCache.set("1",pickedToTwitter = redditsJson.filter(el => goodOne.redditsList(redditsJson.indexOf(el)).checked))



val tweet : Option[List[RedditJsonData]] = sessionCache.get[List[RedditJsonData]]("1")

def send = Action.async { request =>
//for(i <- 0 to tweet.toList.length) {
val data = Map(
"status" -> "asf"

var rt: RequestToken = new RequestToken(request.session.get("token").get, request.session.get("secret").get)

ws.url("" + tweet.get(0).url).sign(OAuthCalculator(KEY, rt)).post("ignored").map(response => {

Answer Source

In my example you see a Singleton and a Cache. You need to be careful with the imports if they are slightly wrong everything crashes. I didn't get the CacheAPI to work the error needs more attention as it seems.

The singleton:

package controllers.singletons
import javax.inject.Singleton

class Test() {
  val message:String = "Test"

Controller Application:

package controllers
import javax.inject.Inject
import controllers.singletons.Test
import play.api.Play.current
import play.api.cache._
import play.api.mvc._

class Application @Inject()(test:Test)extends Controller {
  def index = Action {
    Cache.set("a", "this is a test")

Controller CacheTest:

package controllers
import play.api.cache.Cache
import play.api.Play.current
import play.api.mvc.{Action, Controller}

class CacheTest  extends Controller{
  def cache = Action {

    Ok(views.html.cacheWorks(Cache.get("a").getOrElse("Not Working").asInstanceOf[String]))

I have two routes

GET     /                           controllers.Application.index
GET     /cache                      controllers.CacheTest.cache

And there are two HTML pages which are getting the cache and singleton content and display it. I think that is what you can see from the code, which is pretty straight forward.