Skip to content

Commit

Permalink
don't invoke callback on subscribe in multiplayer mode unless client …
Browse files Browse the repository at this point in the history
…is already connected
  • Loading branch information
nicolodavis committed Oct 25, 2019
1 parent 9596fa4 commit 3206548
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ class _ClientImpl {
this.debug = debug;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;

this.reducer = CreateGameReducer({
game: this.game,
Expand Down Expand Up @@ -320,6 +321,8 @@ class _ClientImpl {

start() {
this.transport.connect();
this.notifySubscribers();
this._running = true;

if (
process.env.NODE_ENV !== 'production' &&
Expand All @@ -341,6 +344,7 @@ class _ClientImpl {

stop() {
this.transport.disconnect();
this._running = false;

if (this._debugPanel != null) {
this._debugPanel.$destroy();
Expand All @@ -352,7 +356,10 @@ class _ClientImpl {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribe(() => this.notifySubscribers());
fn(this.getState());

if (this._running || !this.multiplayer) {
fn(this.getState());
}

// Return a handle that allows the caller to unsubscribe.
return () => {
Expand Down
25 changes: 25 additions & 0 deletions src/client/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,31 @@ describe('subscribe', () => {
client.transport.callback();
expect(fn).toHaveBeenCalled();
});

describe('multiplayer', () => {
test('subscribe before start', () => {
const fn = jest.fn();
const client = Client({
game: {},
multiplayer: { local: true },
});
client.subscribe(fn);
expect(fn).not.toBeCalled();
client.start();
expect(fn).toBeCalled();
});

test('subscribe after start', () => {
const fn = jest.fn();
const client = Client({
game: {},
multiplayer: { local: true },
});
client.start();
client.subscribe(fn);
expect(fn).toBeCalled();
});
});
});

test('override game state', () => {
Expand Down

0 comments on commit 3206548

Please sign in to comment.