Reputation: 1206
I thought this would be a very basic question, but after searching the net, I couldn't find a solution.
I'd like to store a variable somewhere and refer to it later in a function.
The problem I'd like to solve is the following:
I do a HTTP Request to get an accesstoken for an API. This Token is only valid for some time and I only want to get a new token when the old one is expired.
I Need this Token to do other requests.
So I have to store the token and the time it is valid somewhere to access it in other functions, where I to the other requests.
Upvotes: 5
Views: 3058
Reputation: 533
This Token is only valid for some time and I only want to get a new token when the old one is expired
Use ets module for such the things: http://elixir-lang.org/getting-started/mix-otp/ets.html
There are no global/module variables in Elixir (and in other functional languages), because such variables cause race conditions.
Upvotes: 3
Reputation: 2506
I went through something like this as well recently, and the reason it seems like it should be simple was because I was trying to make Elixir act like an object oriented language. There really isn't an easy way to do this out of the box.
What you need to do (I think) is create a module that uses gen_server. There you can put the code to go get your api key and also the code to refresh it after a period of time.
Check out this pseudocode
defmodule APIKey do
use GenServer
def init(_) do
IO.puts "init was called"
# code to go get the api key
apikey = "blahblahblah"
:timer.send_interval(1_400_000, :cleanup)
{:ok, apikey}
end
def handle_call({:get}, _, state) do
IO.puts "handle_call was called"
{:reply, state, state}
end
def handle_info(:refresh, state) do
# put some code here to refresh the api key
end
def start do
GenServer.start(APIKey, nil)
end
def get(pid) do
IO.puts "get was called"
GenServer.call(pid, {:get})
end
end
Call it by doing something like {:ok, pid} = APIKey.start
. Every 1,400,000 seconds it will run the cleanup code and get a new apikey. You can use the key in your code by running APIKey.get(pid)
Upvotes: 2