From d24a97f99dddc02e288da247137b41bad7e96151 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Tue, 25 Mar 2014 11:57:05 +0100 Subject: Add gun:flush/1 to easily cleanup the mailbox It can cleanup all messages from a pid, or just the ones from a specific stream. The latter is useful in combination with cancel/2. --- src/gun.erl | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'src/gun.erl') diff --git a/src/gun.erl b/src/gun.erl index d751b59..e4a919d 100644 --- a/src/gun.erl +++ b/src/gun.erl @@ -49,6 +49,9 @@ -export([await_body/3]). -export([await_body/4]). +%% Flushing gun messages. +-export([flush/1]). + %% Cancelling a stream. -export([cancel/2]). @@ -287,6 +290,44 @@ await_body(ServerPid, StreamRef, Timeout, MRef, Acc) -> {error, timeout} end. +-spec flush(pid() | reference()) -> ok. +flush(ServerPid) when is_pid(ServerPid) -> + flush_pid(ServerPid); +flush(StreamRef) -> + flush_ref(StreamRef). + +flush_pid(ServerPid) -> + receive + {gun_response, ServerPid, _, _, _, _} -> + flush_pid(ServerPid); + {gun_data, ServerPid, _, _, _} -> + flush_pid(ServerPid); + {gun_push, ServerPid, _, _, _, _, _, _} -> + flush_pid(ServerPid); + {gun_error, ServerPid, _, _} -> + flush_pid(ServerPid); + {gun_error, ServerPid, _} -> + flush_pid(ServerPid); + {'DOWN', _, process, ServerPid, _} -> + flush_pid(ServerPid) + after 0 -> + ok + end. + +flush_ref(StreamRef) -> + receive + {gun_response, _, StreamRef, _, _, _} -> + flush_ref(StreamRef); + {gun_data, _, StreamRef, _, _} -> + flush_ref(StreamRef); + {gun_push, _, StreamRef, _, _, _, _, _} -> + flush_ref(StreamRef); + {gun_error, _, StreamRef, _} -> + flush_ref(StreamRef) + after 0 -> + ok + end. + %% Cancelling a stream. -spec cancel(pid(), reference()) -> ok. -- cgit v1.2.3