本文介绍了如何停止执行firebase查询observe(eventType:with :)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试查找此内容,但是找不到停止执行 observe 类型的firebase查询的方法.每次引用更新数据库时,Observe都会进行回调并保持运行.但是我想在视图消失时停止运行该回调,并在视图出现时再次开始运行查询.

I tried looking this up but could not find a way to stop the execution of a firebase query of type observe. Observe takes a call back and keeps running it every time the database is updated at a reference. But I want to stop this callback from running when the view disappears and again start running the query when view will appear.

这就是我想要做的.不幸的是,observe函数返回的是int,而不是可用于停止查询执行的任何处理程序.

So this is what I want to do. Unfortunately the observe functions returns an int and not any handler that can be used to stop the query's excution.

func viewWillDissappear(animated: Bool) {
  ...
  stopQuery()
}

func viewWillAppear(animated: Bool) {
  ...
  startQuery()
} 

func startQuery() {
  Database.database().reference().observe(.value) { (snapshot) in
   //Rest of callback to be executed only when view will appear and is visible
  }
}

func stopQuery() {
   //Stop query callback execution started by startQuery
}

注意:我不希望依赖于使用vairble来检查视图是否可见并跳过回调执行的答案.我想完全取消当前正在运行的查询,并在下一次显示视图时重新启动它.

Note: I don't want answers that rely on using a vairble to check if view is visible and skip the callback execution. I want to compeletly cancel the currently running query and restart it the next time view will appear.

推荐答案

Swift中的句柄 FIRDatabaseHandle 又名 DatabaseHandle 被定义为:

The handle FIRDatabaseHandle aka DatabaseHandle in Swift is defined as:

typedef NSUInteger FIRDatabaseHandle NS_SWIFT_NAME(DatabaseHandle);

因此,您实际上对这是一个整数是正确的.但是最好将返回的句柄存储到一个强变量句柄中,以便可以从 stopQuery()函数中停止/删除观察者.

Therefore, you're actually correct about this being an integer. But it's best if you store the returned handle to a strong variable handle, so that you can stop/remove the observer from your stopQuery() function.

像这样:

// MARK: - Properties

private var handle: DatabaseHandle?

// MARK: - Functions
...
...

func startQuery() {
  handle = Database.database().reference().observe(.value) { (snapshot) in
   //Rest of callback to be executed only when view will appear and is visible
  }
}

func stopQuery() {
   //Stop query callback execution started by startQuery.
        Database.database().reference()
            .removeObserver(withHandle: handle)
}

请记住,您需要跟踪整个路径(即特定的孩子).否则,您可能无法删除观察者.

Remember that you need to track your whole path (ie specific child)., otherwise you might fail in removing your observer.

这篇关于如何停止执行firebase查询observe(eventType:with :)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:54