简体   繁体   English

Firebase函数执行和订阅列表,由firebase函数更新

[英]Firebase function execution and subscription to list that is being updated by a firebase function

I think a firebase function updating a list that I have in the firebase database is being captured by a subscription that is subscribed to that list. 我认为更新我在firebase database的列表的firebase function正被订阅该列表的subscription捕获。 From what the list output looks like on my phone (in the app)...and from what my console output looks like (the way it repeats) it seems like it is capturing the whole list and displaying it each time one is added. 从我的手机上的列表输出(在应用程序中)......以及我的控制台输出的样子(重复的方式)来看,它似乎是捕获整个列表并在每次添加时显示它。 So (I looked this up)...I believe this equation represents what is happening: 所以(我看了一下)......我相信这个等式代表了正在发生的事情:

(N(N + 1))/2

It is how you get the sum of all of the numbers from 1 to N. Doing the math in my case (N = 30 or so), I get around 465 entries...so you can see it is loading a ton, when I only want it to load the first 10. 这是你如何得到从1到N的所有数字的总和。在我的情况下进行数学计算(N = 30左右),我得到大约465个条目...所以你可以看到它正在加载吨,当我只想加载前10个。

To show what is happening with the output here is a pastebin https://pastebin.com/B7yitqvD . 要显示输出的内容,请输入一个pastebin https://pastebin.com/B7yitqvD

In the output pay attention to the array that is above/before length - 1 load . 在输出中注意length - 1 load之上/之前的数组length - 1 load You can see that it is rapidly returning an array with one more entry every time and adding it to the list. 您可以看到它每次都会快速返回一个包含一个条目的数组并将其添加到列表中。 I did an extremely rough count of how many items are in my list too, and I got 440...so that roughly matches the 465 number. 我对我的列表中有多少项目做了非常粗略的计算,我得到了440 ...所以大致与465号码匹配。

The chain of events starts in a page that isn't the page with the list with this function - which initiates the sorting on the firebase functions side: 事件链在一个页面中开始,该页面不是具有此函数的列表的页面 - 它启动firebase functions端的排序:

let a = this.http.get('https://us-central1-mane-4152c.cloudfunctions.net/sortDistance?text='+resp.coords.latitude+':'+resp.coords.longitude+':'+this.username);  
this.subscription6 = a.subscribe(res => {
console.log(res + "response from firesbase functions");
    loading.dismiss();
}, err => {
    console.log(JSON.stringify(err))
    loading.dismiss();
})

Here is the function on the page with the list that I think is capturing the entire sort for some reason. 这是页面上的函数,我认为list由于某种原因捕获整个排序。 The subscription is being repeated as the firebase function sorts, I believe. 我相信,随着firebase function排序,订阅会重复进行。

loadDistances() {
    //return new Promise((resolve, reject) => {
      let cacheKey = "distances"
      let arr = [];
      let mapped;
      console.log("IN LOADDISTANCES #$$$$$$$$$$$$$$$$$$$$$");


      console.log("IN geo get position #$$$$$$$5354554354$$$$$$$");

        this.distancelist = this.af.list('distances/' + this.username, { query: {
          orderByChild: 'distance',
          limitToFirst: 10
        }});


        this.subscription6 = this.distancelist.subscribe(items => {
           let x = 0;

           console.log(JSON.stringify(items) + "      length - 1 load");



           items.forEach(item => {
             let storageRef = firebase.storage().ref().child('/settings/' + item.username + '/profilepicture.png');

              storageRef.getDownloadURL().then(url => {
                console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
                item.picURL = url;
              }).catch((e) => {
                console.log("in caught url !!!!!!!$$$$$$$!!");
                item.picURL = 'assets/blankprof.png';
              });

             this.distances.push(item);

             if(x == items.length - 1) {
               this.startAtKey4 = items[x].distance;
             }

             x++;
           })

           //this.subscription6.unsubscribe();
      })

  }

The subscription in loadDistances function works fine as long as I don't update the list from the other page - another indicator that it might be capturing the whole sort and listing it repeatedly as it sorts. 只要我不从另一个页面更新列表, loadDistances函数中的subscriptionloadDistances正常工作 - 这可能是捕获整个排序并在排序时重复列出的另一个指示。

I have tried as as I could think of to unsubscribe from the list after I update...so then I could just load the list of 10 the next time the page with the list enters, instead of right after the update (over and over again). 我已经尝试过,因为我可以想到在更新后unsubscribe列表...所以我可以在下一次列表页面进入时加载列表10,而不是在更新后立即加载(一遍又一遍)再次)。 I know that firebase functions is in beta . 我知道firebase functions处于beta Could this be a bug on their side? 这可能是他们身边的错误吗? Here is my firebase functions code: 这是我的firebase functions代码:

exports.sortDistance = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
    var array = req.query.text.split(':');
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  // Get a database reference to our posts
    var db = admin.database();
    var ref = db.ref("profiles/stylists");
    var promises = [];
    // Attach an asynchronous callback to read the data at our posts reference
    ref.on("value", function(snapshot) {
      //console.log(snapshot.val());
      var snap = snapshot.val();
      for(const user in snap) {
        promises.push(new Promise(function(resolve, reject) {
            var snapadd = snap[user].address;
            console.log(snapadd + " snap user address (((((((())))))))");
            if(snapadd != null || typeof snapadd != undefined) {
                    googleMapsClient.geocode({
                      address: snapadd
                    }).asPromise()
                        .then(response => { 
                          console.log(response.json.results[0].geometry.location.lat);


                          console.log("  +++   " + response.json.results[0].geometry.location.lat + ' ' + response.json.results[0].geometry.location.lng + ' ' + array[0] + ' ' + array[1]);


                          var distanceBetween = distance(response.json.results[0].geometry.location.lat, response.json.results[0].geometry.location.lng, array[0], array[1]);
                          console.log(distanceBetween + "      distance between spots");
                          var refList = db.ref("distances/"+array[2]);
                          console.log(snap[user].username + "    snap username");
                          refList.push({ 
                            username: snap[user].username,
                            distance: Math.round(distanceBetween * 100) / 100
                          })

                          resolve();
                        })
                        .catch(err => { console.log(err); resolve();})
            }
            else {
                resolve();
            }   
        }).catch(err => console.log('error from catch   ' + err)));
        //console.log(typeof user + 'type of');

      }

      var p = Promise.all(promises);
      console.log(JSON.stringify(p) +     "     promises logged");

      res.status(200).end();

    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });
});

What is weird is, when I check the firebase functions logs, all of this appears to only run once...but I still think the subscription could be capturing the whole sorting process in some weird way while rapidly returning it. 奇怪的是,当我检查firebase functions日志时,所有这些似乎只运行一次......但我仍然认为订阅可能会以一种奇怪的方式捕获整个排序过程,同时快速返回它。 To be as clear as possible with what I think is going on - I think each stage of the sort is being captured in an (N(N + 1))/2 ...starting at 1 and going to roughly 30...and the sum of the sorting ends up being the length of my list (with 1-10 items repeated over and over again). 为了尽可能清楚我认为正在发生的事情 - 我认为这种类型的每个阶段都是在(N(N + 1))/2中捕获的......从1开始到大约30 ......并且排序的总和最终是我的列表的长度(一遍又一遍地重复1-10个项目)。

I updated to angularfire2 5.0 and angular 5.0 ...which took a little while, but ended up solving the problem: 我更新到angularfire2 5.0angular 5.0 ...花了一点时间,但最终解决了问题:

this.distanceList = this.af.list('/distances/' + this.username,
  ref => ref.orderByChild("distance").limitToFirst(50)).valueChanges();

In my HTML I used an async pipe, which solved the sorting problem: 在我的HTML我使用了async管道,解决了排序问题:

...

<ion-item *ngFor="let z of (distanceList|async)" no-padding>

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM