diff --git a/lib/ld-eventsource/client.rb b/lib/ld-eventsource/client.rb index f398b16..28c3a44 100644 --- a/lib/ld-eventsource/client.rb +++ b/lib/ld-eventsource/client.rb @@ -52,6 +52,8 @@ class Client # The default HTTP method for requests. DEFAULT_HTTP_METHOD = "GET" + THREAD_NAME = 'LD/SSEClient' + # # Creates a new SSE client. # @@ -97,6 +99,9 @@ class Client # @param http_client_options [Hash] (nil) additional options to pass to # the HTTP client, such as `socket_factory` or `proxy`. These settings will override # the socket factory and proxy settings. + # @param async [Boolean] (true) whether to run the stream in a separate thread + # if true, the stream will be run in a separate thread + # if false, the stream will be run in the current thread # @yieldparam [Client] client the new client instance, before opening the connection # def initialize(uri, @@ -112,7 +117,8 @@ def initialize(uri, method: DEFAULT_HTTP_METHOD, payload: nil, retry_enabled: true, - http_client_options: nil) + http_client_options: nil, + async: true) @uri = URI(uri) @stopped = Concurrent::AtomicBoolean.new(false) @retry_enabled = retry_enabled @@ -167,7 +173,11 @@ def initialize(uri, yield self if block_given? - Thread.new { run_stream }.name = 'LD/SSEClient' + if async + Thread.new { run_stream }.name = THREAD_NAME + else + run_stream + end end # diff --git a/spec/client_spec.rb b/spec/client_spec.rb index 62c4968..e01de39 100644 --- a/spec/client_spec.rb +++ b/spec/client_spec.rb @@ -972,4 +972,24 @@ def test_object.to_s end end end + + describe "async parameter" do + let(:uri) { "http://example.com/stream" } + + it "creates worker thread when async is true" do + allow_any_instance_of(SSE::Client).to receive(:run_stream) + expect(Thread).to receive(:new).and_call_original + + client = subject.new(uri, async: true) + client.close + end + + it "does not create worker thread when async is false" do + allow_any_instance_of(SSE::Client).to receive(:run_stream) + expect(Thread).not_to receive(:new) + + client = subject.new(uri, async: false) + client.close + end + end end