对LiveData Observe感到困惑

问题描述 投票:0回答:1

我的情况是当用户输入加载片段时,检查LoggedIn,true直接进入MainFragment,false跳转到LoginFramgnet。这是LoadingFragment:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Logger.t(LoadingFragment::class.java.simpleName).i("onCreateView")
        val binding = LoadingFragmentBinding.inflate(inflater, container, false)
        subscribeUi()
        return binding.root
    }

    fun subscribeUi(){
        val factory: LoadingViewModelFactory = InjectorUtils.provideLoadingViewModelFactory()
        val viewModel: LoadingViewModel = ViewModelProviders.of(this, factory).get(LoadingViewModel::class.java)
        Logger.t(LoadingFragment::class.java.simpleName).i("viewModel = " + viewModel.toString())
        viewModel.checkLogin()
        viewModel.isToLogin.observe(viewLifecycleOwner, Observer {
            if (it){
                findNavController().navigate(R.id.action_loading_fragment_to_garden_fragment)
            }else{
                Logger.t(LoadingFragment::class.java.simpleName).i("to start login")
                findNavController().navigate(R.id.start_login)
            }
        })

    }

这是LoadingViewModel:

class LoadingViewModel(
        private val loadingRepository: LoadingRepository
) : ViewModel() {

    val isToLogin: MediatorLiveData<Boolean> = MediatorLiveData()

    fun checkLogin(){
        isToLogin.addSource(loadingRepository.checkLogin()) {
            isToLogin.value = it
        }
    }
}

这是Loadingrepository:

fun checkLogin() : MutableLiveData<Boolean> {
        val data: MutableLiveData<Boolean> = MutableLiveData()
        api.httpGet(SDBUrl.CHECK_LOGIN).enqueue(object : Callback<Map<String, Any>>{
            override fun onFailure(call: Call<Map<String, Any>>, t: Throwable) {
                data.value = false
            }

            override fun onResponse(call: Call<Map<String, Any>>, response: Response<Map<String, Any>>) {
                val result = response.body()
                if (result != null && result.containsKey("success")){
                    val isLogin = result["success"] as Boolean
                    data.value = isLogin
                }else{
                    data.value = false
                }
            }
        })
        return data
    }

登录时,popbackto LoadingFragment,isToLogin立即执行else执行,LoginFragment启动agagin。当我调试时,在LoginFragment popBackStack上等待一段时间,然后goback加载片段,isToLogin观察执行true.so我很困惑,我该如何解决这个问题。

android-livedata android-jetpack android-viewmodel
1个回答
0
投票

最后,我解决了这个问题如下。

class LoadingViewModel(
        private val loadingRepository: LoadingRepository
) : ViewModel() {

    fun checkLogin(): MediatorLiveData<Boolean> {
        val isToLogin : MediatorLiveData<Boolean> = MediatorLiveData()
        isToLogin.addSource(loadingRepository.checkLogin()) {
            Logger.t(LoadingViewModel::class.java.simpleName).i("it = $it")
            isToLogin.value = it
        }
        return isToLogin
    }

}

然后在LoadingFragment中:

loadingViewModel.checkLogin().observe(viewLifecycleOwner, Observer {
            Logger.i("isToLogin = $it")
            if (it) {

                findNavController().navigate(R.id.action_loading_fragment_to_garden_fragment)
            } else {

                findNavController().navigate(R.id.start_login)
            }
        })
© www.soinside.com 2019 - 2024. All rights reserved.