首页 > 解决方案 > ViewModel 发出多次而不是一次

问题描述

我试图在这个片段中只发出一次,它在我第一次进入这个片段时发出,但是如果我导航到下一个片段并返回,它会再次发出,我不希望这样,因为它会重新获取我的数据,相反,如果我回到这个片段,我想避免重新获取。

分段

 private val viewModel by viewModels<LandingViewModel> {
        VMLandingFactory(
            LandingRepoImpl(
                LandingDataSource()
            )
        )
    }

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val sharedPref = requireContext().getSharedPreferences("LOCATION", Context.MODE_PRIVATE)
        val nombre = sharedPref.getString("name", null)
        location = name!!
    }

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        fetchShops(location)
    }

 private fun fetchShops(localidad: String) {

        viewModel.setLocation(location.toLowerCase(Locale.ROOT).trim())
        viewModel.fetchShopList
            .observe(viewLifecycleOwner, Observer {

                when (it) {

                    is Resource.Loading -> {
                        showProgress()
                    }
                    is Resource.Success -> {
                        hideProgress()
                        myAdapter.setItems(it.data)
                    }
                    is Resource.Failure -> {
                        hideProgress()
                        Toast.makeText(
                            requireContext(),
                            "There was an error loading the shops.",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            })

    }

视图模型

 private val locationQuery = MutableLiveData<String>()

    fun setLocation(location: String) {
        locationQuery.value = location
    }

    val fetchShopList = locationQuery.distinctUntilChanged().switchMap { location ->
        liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
            emit(Resource.Loading())
            try{
                emit(repo.getShopList(location))
            }catch (e:Exception){
                emit(Resource.Failure(e))
            }
        }
        }

在这里,当我转到下一个片段并返回时,位置不会改变。任何想法如何解决这一问题 ?我正在使用导航组件。

标签: androidandroid-fragmentskotlinmvvmandroid-architecture-navigation

解决方案


这就是LiveData工作原理,它会在恢复时始终为您提供最新信息。我建议使用 kotlin Flow,因为这可以满足您的要求,在您完成发射后,您将不再获得更新


推荐阅读