Is it absolutely correct that nil'ing a Firebase DatabaseReference does NOT stop the observation?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-04 04:13:07

问题


In the Awesome that is Firebase, you do this

    var r1: DatabaseReference? = nil

and then this

    r1 = Database.database().reference(withPath: "score/bucks")
    r1!.observe(.childAdded) { snapshot in ... }

and then have fun,

but eventually you must do something like this

private func clearObservations() { // call from viewDidDisappear

    if r1 != nil {

        r1?.removeAllObservers()
        r1 = nil
    }

    if r2 != nil {

        r2?.removeAllObservers()
        r2 = nil
    }

    .. etc etc etc etc etc etc :/ :/
}

{ Critical aside: it's worth noting YOU CAN NOT do that in deinit, you MUST do it in viewDidDisappear }

It does seem pretty incredible that one cannot just

      r1 = nil // and this will remove the observor

Is it honest to goodness the case that:

  • if you just nil a DatabaseReference,
  • i.e. you do NOT bother to removeAllObservors,
  • in fact the observation will just keep going?

Is that right?

I just want to absolutely clarify this and get it down on the record - it will probably help future googlers (interestingly, I couldn't really google up a clear marginalia on this anywhere).

I realize you can put them in a hokey array, etc, but it seems incredible that nil'ing one does not stop the observation?!


Footnote

One thing that's always disturbed me. If you carefully read the doco for removeAllObservors, really all it asserts is that it drops or terminates the closure you added. It doesn't, really, say that removeAllObservors actually has the guts of Firebase in the iPhone, actually call home and stop doing the observation. I spend a lot of time worrying about that detail.


回答1:


As I explained in the comments, you must remove observers manually because Firebase hold references to your DatabaseReference and to your closures. If you nil the DatabaseReference it's not deallocating it, it has another reference to it.

I guess from the docs that this what's happening

Many times you'll see in the docs:

Use removeObserverWithHandle: to stop receiving updates.

So this is the way, and the only way.



来源:https://stackoverflow.com/questions/47320099/is-it-absolutely-correct-that-niling-a-firebase-databasereference-does-not-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!