Reply To: gen_server get last message in mailbox

Home Forums OTP Questions gen_server get last message in mailbox Reply To: gen_server get last message in mailbox



You could do something like

flush_to_last() -> flush_to_last(none).

flush_to_last(Last) ->
  receive Any -> flush_to_last(Any)
  after 0 -> Last

But that’s not a very good thing to do — what if you receive a message while flush_to_last/0 is running? Your last message will change!

It is better to think through why you feel the need to do this and think up some way to make it unnecessary. You don’t have enough processes breaking the work up, you’ve got weird blocking situations everywhere, you wrote a God Module that becomes a God Process and tries to do everything, you’ve got a single process handling global state (as a directory or something) and its a bottleneck, your receive statement isn’t catching the right stuff (or maybe you need a receive ... Any -> log(Any) end clause at the end), or whatever.

Something is making you think you need to flush to the last message — but that is almost definitely not the case. It might help if you could explain a bit about what purpose this function would serve for you, or the general effect you are trying to achieve.

As your wise 8-bit Nintendo Famicom would have told you: “This isn’t the solution you’re looking for, Mario! Your problem is in another castle!” ;-)

  • This reply was modified 10 months ago by  zxq9.