LiveData不会触发从Fragment观察它

时间:2020-01-17 12:32:23

标签: android fragment viewmodel android-livedata

我有一个片段,它观察ViewModel中包含的LiveData,以在RecyclerView.Adapter中传递信息。 片段中的LiveData不会触发,但是如果我将其移动到Activity中,则会被触发。

这是代码:

class ProfileViewModel : ViewModel() {


private val profileLiveData: MutableLiveData<User> = MutableLiveData(

private val followersPreview: LiveData<Query> =
        Transformations.map(profileLiveData) { profile ->usersApi.getFollowers(profile.followers) }

private val followingPreview: LiveData<Query> =
    Transformations.map(profileLiveData) { profile -> usersApi.getFollowing(profile.following) }

fun getProfile(userDocumentId: String): LiveData<User> {
    usersApi.getProfile(userDocumentId)
        .addSnapshotListener { querySnapshot, firebaseFirestoreException ->
            if (firebaseFirestoreException != null) {
                Log.d("Exception get profile", firebaseFirestoreException.message!!)
                // Handle exception
            }
            val profileUser: User = querySnapshot?.toObject(User::class.java)!!
            profileLiveData.value = profileUser
        }
    return profileLiveData
}
fun getProfileFollowers(): LiveData<Query> {
    return followersPreview
}

}

class ListsProfileFragment : Fragment() {

private lateinit var fragmentListsBinding: FragmentListsProfileBinding

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    fragmentListsBinding = FragmentListsProfileBinding.inflate(layoutInflater)
    return fragmentListsBinding.root
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    val profileViewModel = ViewModelProviders.of(this).get(ProfileViewModel::class.java);
    Log.d("Viewmodel", profileViewModel.toString())
    profileViewModel
        .getProfileFollowers()
        .observe(viewLifecycleOwner,
            Observer {
                it.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
                    val followers = mutableListOf<UserPreview>()
                    querySnapshot?.documents?.forEach { doc ->
                        val follower: UserPreview = UserPreview(
                            doc.get("username") as String,
                            doc.get("profileImage") as String
                        )
                        followers.add(follower)
                    }
                    fragmentListsBinding.recyclerViewFollowers.layoutManager =
                        LinearLayoutManager(this.activity, RecyclerView.HORIZONTAL, false)
                    fragmentListsBinding.recyclerViewFollowers.adapter =
                        AccountsAdapter(followers)
                }
            })
}

有人可以帮助我吗?预先感谢。

0 个答案:

没有答案