From cdcdc07c06a2785d22603fdd2d945e88d7428f51 Mon Sep 17 00:00:00 2001
From: Bruno Windels <brunow@matrix.org>
Date: Mon, 19 Oct 2020 12:57:21 +0200
Subject: [PATCH] fix a crash when switching rooms before the messages have
 loaded

as we were not disposing the timeline view model
(but still not leaking though)
---
 src/domain/session/room/RoomViewModel.js              | 10 ++++------
 src/domain/session/room/timeline/TimelineViewModel.js |  6 +++++-
 2 files changed, 9 insertions(+), 7 deletions(-)

diff --git a/src/domain/session/room/RoomViewModel.js b/src/domain/session/room/RoomViewModel.js
index d401c843..188f3d1c 100644
--- a/src/domain/session/room/RoomViewModel.js
+++ b/src/domain/session/room/RoomViewModel.js
@@ -25,7 +25,6 @@ export class RoomViewModel extends ViewModel {
         const {room, ownUserId} = options;
         this._room = room;
         this._ownUserId = ownUserId;
-        this._timeline = null;
         this._timelineVM = null;
         this._onRoomChange = this._onRoomChange.bind(this);
         this._timelineError = null;
@@ -42,13 +41,12 @@ export class RoomViewModel extends ViewModel {
     async load() {
         this._room.on("change", this._onRoomChange);
         try {
-            this._timeline = this.track(this._room.openTimeline());
-            await this._timeline.load();
-            this._timelineVM = new TimelineViewModel(this.childOptions({
+            this._timelineVM = this.track(new TimelineViewModel(this.childOptions({
                 room: this._room,
-                timeline: this._timeline,
+                timeline: this._room.openTimeline(),
                 ownUserId: this._ownUserId,
-            }));
+            })));
+            await this._timelineVM.load();
             this.emitChange("timelineViewModel");
         } catch (err) {
             console.error(`room.openTimeline(): ${err.message}:\n${err.stack}`);
diff --git a/src/domain/session/room/timeline/TimelineViewModel.js b/src/domain/session/room/timeline/TimelineViewModel.js
index 0f7464f8..5faa23b3 100644
--- a/src/domain/session/room/timeline/TimelineViewModel.js
+++ b/src/domain/session/room/timeline/TimelineViewModel.js
@@ -39,13 +39,17 @@ export class TimelineViewModel extends ViewModel {
     constructor(options) {
         super(options);
         const {room, timeline, ownUserId} = options;
-        this._timeline = timeline;
+        this._timeline = this.track(timeline);
         // once we support sending messages we could do
         // timeline.entries.concat(timeline.pendingEvents)
         // for an ObservableList that also contains local echos
         this._tiles = new TilesCollection(timeline.entries, tilesCreator({room, ownUserId, clock: this.clock}));
     }
 
+    async load() {
+        await this._timeline.load();
+    }
+
     /**
      * @return {bool} startReached if the start of the timeline was reached
      */