代码之家  ›  专栏  ›  技术社区  ›  Bitwise

从GenServer检索所有状态

  •  1
  • Bitwise  · 技术社区  · 7 年前

    我的GenServer中有一个原子数组。我不想只弹出队列中的最后一项,我想一次弹出所有状态。

    当前代码(不工作)

    defmodule ScoreTableQueue do
      use GenServer
    
      @impl true
      def init(stack) do
        {:ok, stack}
      end
    
      @impl true
      def handle_call(:pop, _from, [state]) do
        {:reply, [state]}
      end
    
      @impl true
      def handle_cast({:push, item}, state) do
        {:noreply, [item | state]}
      end
    end
    

    {:status, #PID<0.393.0>, {:module, :gen_server},
     [
       [
         "$initial_call": {ScoreTableQueue, :init, 1},
         "$ancestors": [#PID<0.383.0>, #PID<0.74.0>]
       ],
       :running,
       #PID<0.393.0>,
       [],
       [
         header: 'Status for generic server <0.393.0>',
         data: [
           {'Status', :running},
           {'Parent', #PID<0.393.0>},
           {'Logged events', []}
         ],
         data: [{'State', [:code, :hello, :world]}]
       ]
     ]}
    

    我想回来 [:code, :hello, :world] 当我打电话的时候 GenServer.call(pid, :pop) 我怎样才能做到这一点?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Badu    7 年前

    改变

    @impl true
    def handle_call(:pop, _from, [state]) do
      {:reply, [state]}
    end
    

     @impl true
     def handle_call(:pop, _from, [state]) do
      {:reply, state, []}
     end
    

    基本上就是返回状态并将当前状态设置为空列表

    handle_call/3 返回格式为的元组

    {:reply, reply, new_state}

    在您的情况下,您希望回复当前状态并将新状态设置为空列表。

    {:reply, state, []}

    {:reply, state, state}