jislam
jislam

Reputation: 842

Value of a scala variable do not change while executing play Future query. Why?

I am new to SCALA language and making an API service with play and slick. Look at the following code.

def checkToken(userToken: String): Boolean = {
      var status = false
      Tokens.getToken(userToken).map(
          token => {
            if (token.isDefined && token.get.status.equals("ACTIVE")) {
                status = true
                println("--------------------------------- if: "+status+" -----------------------------")
            } else {
                status = false
                println("--------------------------------- else: "+status+" -----------------------------")
            }
          }
      )
      println("---------------------------------status: "+status+"-----------------------------")
      return status
    }

While executing the above code it shows the following output

---------------------------------status: false-----------------------------
--------------------------------- if: true -----------------------------

But the output should be [both should be true for a valid token]

---------------------------------status: true-----------------------------
--------------------------------- if: true -----------------------------

What is the problem with the above code?

Upvotes: 3

Views: 110

Answers (1)

John K
John K

Reputation: 1285

You have a timing issue.

If getToken returns a Future, when your "main" thread arrives on Tokens.getToken(userToken), it will execute it on a different thread. In the meantime, the main thread keeps on moving, arrives at print("status"+status) before it actually had time to change, and the function returns. Only then does the Future returns at some point and, still on that separate thread, will execute the code inside map and change the value of status.

What I think you want is a function that returns a Future[Boolean] (edited to match @rethab suggestion):

def checkToken(userToken: String): Future[Boolean] = Tokens.getToken(userToken).map(_.contains("ACTIVE"))

Upvotes: 4

Related Questions