samedi 12 septembre 2020

Android - Live data not working with recyclerview

LiveData is not triggering. There are many livedata that I ran in the same fragment but one of them just didn't work. I have no idea what the problem is.

ViewModel.kt (Part of the code has been reduced.)

class MyAccountViewModel : ViewModel() {

    private val _dataUser = MutableLiveData<User>()
    val dataUser: LiveData<User>
        get() = _dataUser

    private val _userState = MutableLiveData<UserViewState>()
    val userState: LiveData<UserViewState>
        get() = _userState

    private val _storiesState = MutableLiveData<StoriesViewState>()
    val storiesState: LiveData<StoriesViewState>
        get() = _storiesState

    private val _dataStories = MutableLiveData<List<Stories>>()
    val dataStories: LiveData<List<Stories>>
        get() = _dataStories

    private val _navigateToStories = MutableLiveData<Long>()
    val navigateToStories: LiveData<Long>
        get() = _navigateToStories

    fun openUserStories(userId: Long) {
        _navigateToStories.postValue(userId)
    }

 }

Fragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
      observe(viewModel.dataUser, ::onViewUserDataChanged) //WORKING
      observe(viewModel.userState, ::onViewUserStateChanged) //WORKING
      observe(viewModel.dataStories, ::onViewStoriesDataChanged) //WORKING 
      observe(viewModel.storiesState, ::onViewStoriesStateChanged) //WORKING
      observe(viewModel.navigateToStories, ::onViewEvent) //NOT WORKING
}

 private fun onViewEvent(viewEvent: Long) {
       findNavController().navigate(
          MyAccountFragmentDirections.
           actionMyAccountFragmentToMediaShowFragment(viewEvent)
        )
 }

observe() Method:

fun <T> LifecycleOwner.observe(liveData: LiveData<T>, observer: (T) -> Unit) {
    liveData.observe(this, Observer {
        it?.let { t -> observer(t) }
    })
}


fun <T> LifecycleOwner.observe(liveData: MutableLiveData<T>, observer: (T) -> Unit) {
    liveData.observe(this, Observer {
        it?.let { t -> observer(t) }
    })
}

onClick with DataBinding (Part of the code has been reduced.):

<androidx.constraintlayout.widget.ConstraintLayout
        android:onClick="@{() -> viewModel.openUserStories(stories.id)}"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

 </androidx.constraintlayout.widget.ConstraintLayout>

Here are the recyclerview items that I applied the onClick method.

enter image description here

Aucun commentaire:

Enregistrer un commentaire