LiveData 不会触发从片段观察它



我有一个片段,它观察ViewModel中包含的LiveData,以便在RecyclerView.Adapter中传递信息。 片段中的实时数据不会触发,但如果我在活动中移动它,它就会被触发。

代码如下:

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)
}
})
}

谁能帮我?提前谢谢。

使用以下代码加载视图模型已解决:

profileViewModel =
activity?.run { ViewModelProviders.of(this).get(ProfileViewModel::class.java) }
?: throw Exception("Invalid Activity")