---
# System prepended metadata

title: 'Firebase with Android Studio part-7 : real-time updates with SnapshotListener'
tags: [Firebase, Android, kotlin]

---

# Firebase with Android Studio part-7 : real-time updates with SnapshotListener

## 開始吧
* 延續上一篇[Part-6](https://hackmd.io/IfgSSfdlRK69rua78RjFaA?view)
* 在Part-6我們需要手動取得資料，這篇要讓它變成real-time自動更新


### MainActivity
* 新增function
* 使用addSnapshotListener
* 在onCreate呼叫這個函數，之後只要docment有變更它會自動更新資料
* 就可以把手動更新的功能拿掉了
```kotlin=
private fun subscribeToRealtimeUpdates(){
        personCollectionRef.addSnapshotListener { value, error ->
            error?.let {
                Toast.makeText(this,it.message,Toast.LENGTH_LONG).show()
                return@addSnapshotListener
            }
            value?.let {
                val sb = StringBuilder()
                it.documents.forEach { doc ->
                    val person = doc.toObject<Person>()
                    sb.append("$person\n")
                }
                findViewById<TextView>(R.id.textView).text = sb.toString()
            }
        }
    }
```

參考資料
[Philipp Lackner's channel](https://www.youtube.com/watch?v=TIub9JMYhDs)


###### tags: `Firebase` `kotlin` `Android`