Android FirestoreUI FirestoreRecyclerAdapter: Runtime Replace Query

Since FirestoreRecyclerAdapter doesn't support change of query, so we need to recreate the adapter when Query changed.

Since FirestoreRecyclerAdapter use addSnapshotListener, we need to call adapter.stopListening (and lifecycle.removeObserver if setLifecycleOwner is used) before replacing the adapter.

class MyActivity:  AppCompatActivity() {    private lateinit var adapter: LocalAdapter    private fun createAdapter(): LocalAdapter {        if (::adapter.isInitialized) {            // call this before replacing the adapter to prevent invalid snapshot            adapter.stopListening()            lifecycle.removeObserver(adapter)        }        val query = ...        // Quote is Model        val builder = FirestoreRecyclerOptions.Builder<Quote>()            .setLifecycleOwner(this)            .setQuery(query, object : SnapshotParser<Quote> {                override fun parseSnapshot(snapshot: DocumentSnapshot): Quote {                    return Quote.toObject(snapshot)!!.also {                        it.id = snapshot.id                    }                }            })        val options = builder.build()        return FirestoreQuoteAdapter(options, viewModel).also {            adapter = it        }    }    private fun initUi() {        recyclerView.adapter = createAdapter()    }}

NOTE: Refer to Android Firestore RecyclerView With FirestoreUI FirestoreRecyclerAdapter for Quote and FirestoreQuoteAdapter implementation.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.