Skip to content

Commit

Permalink
feat(client): Lazy option can be changed
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Sep 5, 2020
1 parent 2d87059 commit fb0ec14
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/client.ts
Expand Up @@ -45,6 +45,12 @@ export interface ClientOptions {
url: string;
/** Optional parameters that the client specifies when establishing a connection with the server. */
connectionParams?: ConnectionParams;
/**
* Should the connection be established immediately and persisted
* or after the first listener subscribed.
* @default true
*/
lazy?: boolean;
}

export interface Client extends Disposable {
Expand All @@ -58,7 +64,7 @@ export interface Client extends Disposable {

/** The internal socket manager. */
function createSocket(options: ClientOptions) {
const { url, connectionParams } = options;
const { url, connectionParams, lazy = true } = options;

let state = {
connecting: false,
Expand Down Expand Up @@ -206,14 +212,18 @@ function createSocket(options: ClientOptions) {
}
}

if (!lazy) {
up();
}

return {
subscribe<E extends Event>(
event: E,
listener: EventListener<E>,
): Disposable {
subscribers.add(event, listener);

if (event === 'message') {
if (lazy && event === 'message') {
up();
}

Expand All @@ -225,9 +235,11 @@ function createSocket(options: ClientOptions) {
return {
dispose: () => {
subscribers.remove(event, listener);

// stop when last message unsubscribe
if (event === 'message' && subscribers.state.message.length === 0) {
if (
lazy &&
event === 'message' &&
subscribers.state.message.length === 0
) {
down();
}
},
Expand Down

0 comments on commit fb0ec14

Please sign in to comment.