Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
testuser Avatar asked Jan 20 '26 10:01

testuser


1 Answers

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"))
like image 60
John K Avatar answered Jan 23 '26 20:01

John K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!