0

我有一个应用程序,它遵循一个带有几个片段的单一活动模式,这些片段使用 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()}")
}

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

当我的应用程序启动时,它直接进入帐户片段。当我单击按钮时,它显示为真。但是,如果我更改抽屉中的片段并返回 accountFragment 并单击按钮,则显示为 false。你能帮忙解释一下为什么我的账户实时数据正在失去观察者吗?

我有另一个cardFragment,它以与帐户片段相同的方式获取数据,并且不会失去其活跃的观察者。我的来源来自 firebase,我可以毫无问题地从中获取数据。它也适用于 cardsFragment 并且代码与帐户片段相同。我只是在帐户片段方面遇到问题。有人可以帮帮我吗?

4

0 回答 0