0
votes

Good morning,

I have a problem when loading a list from firebase and rendering it to my view with AngularFire2.

Explanations:

I have in my page a function allowing to load a list of posts, and to map the posts to the user data, to then bind the whole list to the view :

Timeline.ts:

// Get the timeline data
getTimeline() {
    console.log('Get timeline data');
    this.loadingProvider.show();
    this.createUserData(); // create user data if accoutn just created
    this.dataProvider.getCurrentUser().valueChanges().subscribe((user) => {
      this.user = <any>user;
    });

    this.getUserFriends().then((friends) => {
      this.friends = friends;
    }).then(() => {
      this.dataProvider.getTimelinePost().valueChanges().subscribe((posts) => {
        console.log("Change in timeline");
        this.timelineData = posts.slice(0).reverse().map(p => {
          return this.checkPostData(p);
        });
        this.loadingProvider.hide();
      });

    });
  }

// Get the friend's user so we can display only the post who are relevants for the user
  getUserFriends() {
    return new Promise((resolve) => {
      this.dataProvider.getFriends().valueChanges().subscribe((f) => {
        resolve(f)
      });
    });
  }

// Map post data with user's info such as avatar, etc
  checkPostData(currentPost) {
    let postedByFriend = this.checkIfPostedByFriend(currentPost);
    if (postedByFriend || currentPost.postBy === firebase.auth().currentUser.uid) {
      this.dataProvider.getUser(currentPost.postBy).valueChanges().subscribe((user) => {
        currentPost.avatar = user.img;
        currentPost.name = user.name
      });
      //  Liked ?
      this.dataProvider.getLike(currentPost.key).valueChanges().subscribe((likes) => {
        currentPost.likes = likes.length;
        currentPost.isLike = this.checkIfPostIsLiked(likes);
      });
      //  Disliked ?
      this.dataProvider.getdisLike(currentPost.key).valueChanges().subscribe((dislikes) => {
        currentPost.dislikes = dislikes.length;
        currentPost.isdisLike = this.checkIfPostIsDislike(dislikes);
      });
      // Commented ?
      this.dataProvider.getComments(currentPost.key).valueChanges().subscribe((comments) => {
        currentPost.comments = comments.length;
        currentPost.isComment = this.checkIfPostIsCommented(comments);
      });
    }
    return currentPost;
}

Timeline.html :

    <ion-card *ngFor="let item of timelineData">
    <ion-item >
      <ion-avatar item-left>
        <img src="{{item.avatar}}"  >
      </ion-avatar>
      <h2>{{item.name}}</h2>
      <p>{{item.dateCreated | DateFormat}}</p>
    </ion-item>

    <ion-card-content>
      <p>{{item.postText}}</p>
    </ion-card-content>
    [...]
  </ion-card>

DataProvider.ts :

// Get Timeline post
  getTimelinePost(){
    return this.angularDb.list<any>('/timeline');
  }

My problem is the following: when I add a post to the timeline, it takes a few seconds because the Timeline.ts page reloads the entire list (which is normal because there is a subscription made with getTimeLinePost()). I would like to know if it is possible to detect only the last changes in my list to add them to the view and thus avoid reloading all the data.

I have already tried SnapshotChanges() and StateChange() but without success.

I noticed that when I add a post, the subscription is triggered twice :

Change in timeline (2) timeline.ts:89:8

Addpost.ts code :

pushNewPost(url) {
    this.angularDb.list('timeline').push({
      dateCreated: new Date().toString(),
      postBy: firebase.auth().currentUser.uid,
      postText: this.postText,
      image: url
    })
}

Versions used : "@angular": "5.2.11", "angularfire2":"^5.0.0-rc.5-next",

Any idea for this ? Am I missing something?

thanks in advance

UPDATE :

I found an alternative that has less impact on rendering performance (on the view), but all data is still loaded when a change is triggered on the database:

    getTimeline() {
    console.log('Get timeline data');
    this.loadingProvider.show();
    this.createUserData();
    this.dataProvider.getCurrentUser().valueChanges().subscribe((user) => {
      this.user = <any>user;
    });

    this.getUserFriends().then((friends) => {
      this.friends = friends;
    }).then(() => {
      this.dataProvider.getTimelinePost().snapshotChanges().map(actions =>
        actions.map(a => ({ type: a.type, ...a.payload.val() }))
      ).subscribe(items => {
        this.checkPostData(items);
        this.loadingProvider.hide();
      });
    });
  }

  getUserFriends() {
    return new Promise((resolve) => {
      this.dataProvider.getFriends().valueChanges().subscribe((f) => {
        resolve(f)
      });
    });
  }

  checkPostData(currentPost) {
   // Check if whe have a child added to the timeline
    if (this.timelineLoaded === true) {
      currentPost.forEach(p => {
        if (p.type === 'child_added') {
          this.mapPost(p);
        }
      });
    } else {
      this.timelineData = [];
      currentPost.map(p => {
        return this.mapPost(p);
      });
    }
  }

  mapPost(currentPost) {
    let postedByFriend = this.checkIfPostedByFriend(currentPost);
    if (postedByFriend || currentPost.postBy === firebase.auth().currentUser.uid) {
      this.dataProvider.getUser(currentPost.postBy).valueChanges().subscribe((user) => {
        currentPost.avatar = user.img;
        currentPost.name = user.name
      });
      //  Liked ?
      this.dataProvider.getLike(currentPost.key).valueChanges().subscribe((likes) => {
        currentPost.likes = likes.length;
        currentPost.isLike = this.checkIfPostIsLiked(likes);
      });
      //  Disliked ?
      this.dataProvider.getdisLike(currentPost.key).valueChanges().subscribe((dislikes) => {
        currentPost.dislikes = dislikes.length;
        currentPost.isdisLike = this.checkIfPostIsDislike(dislikes);
      });
      // Commented ?
      this.dataProvider.getComments(currentPost.key).valueChanges().subscribe((comments) => {
        currentPost.comments = comments.length;
        currentPost.isComment = this.checkIfPostIsCommented(comments);
      });
      this.timelineData.unshift(currentPost);
      this.timelineLoaded = true
    }
    return currentPost;
  }
1

1 Answers

0
votes

There is no handy way to do this in my experience.

But since it is a timeline, list changes will always be child add. You can do something like this :

  this.timelineData = [];

  this.dataProvider.getTimelinePost().valueChanges().subscribe((posts) => {
    posts.forEach(p => {
      if (!this.timelineData.find(data => data.dateCreated === p.dateCreated)) {
        const elem = this.checkPostData(p);

        // this will put it in front of the list, don't need to reverse
        this.timelineData.unshift(elem);
      }
    })
  });

By the way, you shouldn't make subscribe in a subscribe, nor subscribe to create a promise.

Let's consider :

const obs1$ = afDb.object(ANYREF).valueChanges();

obs1$.subscribe(data => {
  const obs2$ = afDb.object(data).valueChanges();
  obs2$.subscribe(a => console.log(a));
});

This will work but anytime obs1$ does trigger, obs2$ will be "re"subscribed.

ie: if there are 5 changes on obs1$, you will have 5 obs2$' subscriptions. every new obs2$ changes, you will have 5 times the console.log..., this is a memory leak

A fix maybe using the take(1) operator. This can force the subscription to be triggered once.

const obs1$ = afDb.object(ANYREF).valueChanges();

obs1$.subscribe(data => {
  const obs2$ = afDb.object(data).valueChanges();

  // Rxjs 5 way :
  obs2$.take(1).subscribe(a => console.log(a));
  // Rxjs 6 way :
  obs2$.pipe(take(1)).subscribe(a => console.log(a));
});

obs2$ will always be triggered once and no memory leaks but you won't have "live database data" with obs2$.

a better way :

const obs1$ = afDb.object(ANYREF).valueChanges();

// Rxjs 5 way :
obs1$.switchMap(data => afDb.object(data).valueChanges())
  .subscribe(a => console.log(a));
// Rxjs 6 way :
obs1$.pipe(switchMap(data => afDb.object(data).valueChanges()))
  .subscribe(a => console.log(a));

With this method you'll keep both observables "live binded" to your database without leak. (Except the one created because it is never unsubscribed).

You may do this :

// ionViewWillEnter
const obs1$ = afDb.object(ANYREF).valueChanges();
this.sub = obs1$.pipe(switchMap(data => afDb.object(data).valueChanges()))
  .subscribe(a => console.log(a));

// ionViewWillLeave
this.sub.unsubscribe();

If you don't, your subscriptions will be kept alive, whenever you're not on the same page.

Your code seems really complicated to me but if you're a "by example learner", you may refer to this doc : https://www.learnrxjs.io/