我正在尝试在自己的MainViewModel中保存一个“情节”,并允许其他Fragments通过该ViewModel访问它。

MainActivity中,我观察到ViewModel的变化,该变化从未触发。奇怪的是,对于我的MainFeed RSS对象来说,它工作正常

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(MainViewModel::class.java)


    mViewModel?.getMainFeed()

    setFragment(EpisodesFragment(), false)

    mViewModel?.episode?.observe(this, Observer {
        Log.d(TAG, "HERE 123")
    })
}

这是MainViewModel:
class MainViewModel @Inject constructor(): ViewModel() {
    val TAG: String? = MainViewModel::class.simpleName

    @Inject lateinit var api: NetworkModule

    var mainFeed: MutableLiveData<Response<RSS>> = MutableLiveData()
    var episode: MutableLiveData<Item> = MutableLiveData()

    companion object{
        fun create(activity: FragmentActivity, viewModelFactory: ViewModelProvider.Factory): MainViewModel {
            return ViewModelProviders.of(activity, viewModelFactory).get(MainViewModel::class.java)
        }
    }

    fun getMainFeed(){
        GlobalScope.launch(Dispatchers.Main) {
            val request = api.getRssFeed()
            val response = request.await()

            if(response.isSuccessful){
                Log.d(TAG, "isSuccessful")

                mainFeed.value = response
            } else {
                Log.d(TAG, "not successful")
            }
        }
    }

    fun setEpisode(item: Item?){
        Log.d(TAG, item?.description)
        episode?.value = item
    }
}

在我的EpisodesFragment中,我将MainViewModel传递给RecyclerView适配器。在“情节”项目的布局中,我有一个称为onClick()mViewModel.setEpisode(episode)
因此,点击次数正在增加。我设置了断点,可以看到情节项目实际上在那里,并在setEpisode()方法中保存了数据。它实际上从未设置过LiveData。我验证了ViewModel在我使用过的任何位置都不为空。

编辑:为EpisodesFragment添加代码
class EpisodesFragment @Inject constructor() : DaggerFragment() {
    var TAG: String? = EpisodesFragment::class.simpleName

    var mBinding: FragmentEpisodesBinding? = null
    var mRV: RecyclerView? = null
    var mAdapter: EpisodesRecyclerViewAdapter? = null

    var mItems: MutableList<Item> = ArrayList<Item>()

    @Inject
    lateinit var mViewModelFactory: ViewModelProvider.Factory
    var mViewModel: EpisodesViewModel? = null
    var mMainViewModel: MainViewModel? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_episodes, container, false)
        mBinding?.executePendingBindings()


        return mBinding?.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        mViewModel = ViewModelProviders.of(this,
            mViewModelFactory
        ).get(EpisodesViewModel::class.java)

        mMainViewModel = ViewModelProviders.of(
            this,
            mViewModelFactory
        ).get(MainViewModel::class.java)

        if (mBinding?.rv != null) {
            mRV = mBinding?.rv
            val context: Context? = mRV?.context

            mRV?.setHasFixedSize(true)

            mAdapter = EpisodesRecyclerViewAdapter(mMainViewModel)

            mRV?.adapter = mAdapter

            val layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            val dividerItemDecoration = DividerItemDecoration(
                mRV?.context,
                layoutManager.orientation
            )
            mRV?.addItemDecoration(dividerItemDecoration)
            mRV?.layoutManager = layoutManager

        }

        mViewModel?.getMainFeed()

        mViewModel?.mainFeed?.observe(viewLifecycleOwner, Observer {
            mItems.addAll(it?.body()?.channel?.item!!)

            Log.d(TAG, mItems.get(0).description)
            mAdapter?.setItems(mItems)
            mAdapter?.notifyDataSetChanged()
        })
    }
}

最佳答案

请求activity时,尝试在this中使用EpisodesFragment属性而不是MainViewModel:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    mMainViewModel = ViewModelProviders.of(
        activity,
        mViewModelFactory
    ).get(MainViewModel::class.java)

    // ...
}
ViewModelProviders.of可能为片段返回不同的MainViewModel实例。

关于android - 未设置LiveData,从未调用观察者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54224678/

10-10 01:42