Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

ios - Firebase: when to call removeObserverWithHandle in swift

Documentation says you need to call observeEventType:withBlock to remove an observer if you no longer need it.

I've seen samples where it is called within ViewDidDisAppear. I also find some Obj-C code called this method within deinit, which is not ncessary in Swift.

In my simple app, however, I want data to be synced as long as I am in the app. If this is the case, do I have to call observeEventType:withBlock ever?

I checked the Chat-Swift sample code on Firebase website, and did not find observeEventType:withBlock.

Does it mean it's ok not to call observeEventType:withBlock:. if I want the observer to be on when the app is in use?

Thank you.

UPDATE

Thanks to Jay and David. I see it makes sense to observe in ViewWillAppear and remove it in ViewDidDisappear.

However, I am using observeEventType to monitor any value change to the node and would update UI if there is any. If i put it in ViewWillAppear:

 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    ref.observeEventType(.Value, withBlock: { snap in {
      // **update UI if there is any Value change** 
    })
  }

The problem with putting it in viewWillAppear is that, it gets called every time the view appears, regardless of Value change or not. Because of this, the snapshot is downloaded and my UI gets refreshed every time I return to the view. This becomes counterproductive.

I have also tried ChildAdded/ChildRemoved, however, it only returns the last node, not the path from my ref:

For instance, if I add to ref/child1/child2/child3/value, ChildAdded would only return child3/value.

So if I have to observe Value, it seems like putting it in ViewDidLoad is better? In this way, it gets the snapshot one time when the view loaded, and would repeat whenever there is a change, but would not obtain the snapshot just because the view appears.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...