2017-07-30 55 views
0

我曾經打電話observe.value這會加載查詢中的所有子項。實時,當一個孩子不再是查詢的一部分時(即其時間戳太舊),該事件將被解僱,並且孩子的數據將從我的應用程序中刪除。爲了達到性能目的,我不單獨使用.valueobserve聯繫,而是分別觀察.childAdded,.childChanged.childRemoved事件。但是,當孩子不再是查詢的一部分時,這些事件都不會被觸發,並且孩子的數據仍然保存在我的應用程序中。我試過觀察.childMoved,但那也沒有被解僱。我該如何複製觀察.value的這一方面?下面是代表我的一些代碼:Firebase刪除不再是查詢的一部分的子女

class ViewController: UIViewController { 

    var children_query: DatabaseQuery! 
    var current_time: TimeInterval { 
     return Date().timeIntervalSince1970 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time) 
    } 

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

     // refresh query every time this view appears (this is the root view controller so it comes and goes) 
     self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time) 

     self.children_query.observe(.childAdded, with: { snapshot in 
      print(snapshot.value) 
     }) 

     self.children_query.observe(.childChanged, with: { snapshot in 
      print(snapshot.value) 
     }) 

     self.children_query.observe(.childRemoved, with: { snapshot in 
      print(snapshot.value) 
     }) 

     self.children_query.observe(.childMoved, with: { snapshot in 
      print(snapshot.value) 
     }) 
    } 

    override func viewDidDisappear(_ animated: Bool) { 
     super.viewDidDisappear(animated) 
     self.children_query.removeAllObservers() 
    } 
} 

回答

0

我給你在這種情況下的簡單解決方案。只需將直接父項添加到所有值。

rootNode: [ 
    { your first value } 
    { your second value } 
.... 
    /* you can add value here */ 
    {your last value } 
      ] 

現在,您不是觀察每個值,而是觀察它們的直接父母。這樣,從dataSnapshot的定義中無論內部變化如何,它都會觸發onMessageReceived()函數。

+0

我不確定我是否遵循 –

+0

@ArchieGertsman,爲確切證明,請在此頁查看此視頻。他談到DataSnapshot。 https://firebase.google.com/docs/web/setup –

+0

@ArchieGertsman,在那個rootNode裏面的任何東西都被改變了,並且在rootNode上觀察,然後根據DataSnapshot的定義,onMessageReceived()回調會在你身邊觸發。我對此100%肯定。 –