I was using Query.addSnapshotListener in a Fragment
class TestFragment : Fragment() { override fun onActivityCreated(savedInstanceState: Bundle?) { val query = ... query.addSnapshotListener(activity!!) { querySnapshot, e -> } }}
and bump into the following exception
java.lang.IllegalStateException: FragmentManager is already executing transactions at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
The error doesn't happend instantly. If I launch the App, pressed back (app goes into background) and launch the app again, the error will occur. Similar incidents have been reported.
NOTE: I am using com.google.firebase:firebase-firestore:19.0.0
.
Solution 1: ListenerRegistration
class TestFragment : Fragment() { private var queryRegistration: ListenerRegistration? = null override fun onActivityCreated(savedInstanceState: Bundle?) { val query = ... queryRegistration = query.addSnapshotListener { querySnapshot, e -> } } override fun onDestroy() { super.onDestroy() queryRegistration?.also { it.remove() collectionRegistration = null } }}
Solution 2: addSnapshotListener with LifecycleOwner
Use code from Firestore addSnapshotListener with LifecycleOwner.
// this = LifecyclerOwnerquery.addSnapshotListener(this) { documentSnapshot, e ->}
Solution 3: QuerySnapshotLiveData
Use code from Android Firestore Query addSnapshotListener as LiveData.
// this = LifecyclerOwnerquery.asSnapshotLiveData().observe(this, Observer { result -> if (result.isSuccessful) { // do something val query = result.data() } else { Timber.e(result.error()) }})