更改片段时Android LiveData失去了活跃的观察者

时间:2020-05-26 16:27:31

标签: android kotlin android-livedata android-viewmodel android-livedata-transformations

我有一个应用程序,该应用程序遵循单个活动模式,其中包含多个片段,这些片段使用Jetpack导航在抽屉​​中导航。

在一个片段上,我有一个实时数据帐户,可以从片段中观察到这样的数据帐户:

accountFragment.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    //Observe accounts list being updated
    observeAccountsEvent()
}

private fun observeAccountsEvent() {
        with(viewModel) {
            accounts.observe(viewLifecycleOwner, Observer { accounts ->
                if (accounts != null) {
                    //set loading flag to hide progress bar
                    doneLoading()

                //Alternate visibility for account list and empty view
                alternateAccountListVisibility(accounts.size)

                //Submit the cards
                initiateAccountList().submitList(accounts)
            }
        })
    }
}

accountViewModel.kt

private val sortedByName = Transformations.map(_currentAccountsExposed) {
    it.sortedBy { account ->
        account.accountName.toLowerCase(
            Locale.ROOT
        )
    }
}

private val sortedByUsername = Transformations.map(_currentAccountsExposed) {
    it.sortedBy { account ->
        account.username.toLowerCase(
            Locale.ROOT
        )
    }
}
...

init {

    //Load the accounts for the first time
    loadAccounts()

}

val accounts = Transformations.switchMap(_sort) {
    Log.i("ACCOUNT_SORT", "7. Started Transformation...")
    when (true) {
        it.name -> {
            //Log.i("ACCOUNT_SORT", "4. Name sorting...")
            sortedByName
        }
        it.username -> {
            //Log.i("ACCOUNT_SORT", "4. Username sorting...")
            sortedByUsername
        }
        it.email -> {
            //Log.i("ACCOUNT_SORT", "4. Email sorting...")
            sortedByEmail
        }
        it.website -> {
            //Log.i("ACCOUNT_SORT", "4. Website sorting...")
            sortedByWebsite
        }
        it.authType -> {
            //Log.i("ACCOUNT_SORT", "4. Auth Type sorting...")
            sortedByAuthType
        }
        else ->  {
            //Log.i("ACCOUNT_SORT", "2. current sorting...")
            _currentAccountsExposed
        }
    }
}

private fun loadAccounts() {
    _currentAccountsExposed.addSource(AccountDao().getAll(getUserID())) { snapshot ->
        _currentAccountsExposed.value = decomposeDataSnapshots(snapshot)
    }
}

internal fun click() {
  Log.i("ACCOUNT_SORT", "Accounts: ${accounts.hasActiveObservers()}")
}

我有一个按钮,当我单击时会触发视图模型中的单击功能。单击功能会记录帐户实时数据是否具有活动的观察者。

启动我的应用程序时,它直接进入帐户片段。当我单击按钮时,它显示为true。但是,如果我在抽屉中更改片段,然后回到accountFragment并单击按钮,则显示为false。您能帮我为什么我的帐户实时数据丢失其观察者吗?

我还有另一个cardsFragment,它以与帐户片段相同的方式获取数据,并且不会丢失其活动的观察者。我的资源来自firebase,从那里获取数据也没有问题。它对于cardsFragment也可以正常工作,并且代码与帐户片段相同。我在帐户片段方面遇到问题。有人可以帮我吗?

0 个答案:

没有答案