【问题标题】:join firebase model and update live data with combined results加入 firebase 模型并使用组合结果更新实时数据
【发布时间】:2018-12-31 05:37:54
【问题描述】:

HelloBelow 是我的数据库结构

我想首先从 post 对象中获取结果,然后使用“userid”从我想从 Users 对象中获取结果。 我想用上面包含两个对象中的字段的结果更新 ViewModel 如何做到这一点? 我已经编写了代码来从 post 对象中获取结果,但是如何再次调用以获取用户对象并更新 viewmodel 和 livedata 对象

  private static final DatabaseReference POST_REF =
    FirebaseDatabase.getInstance().getReference("/Post");

   private final FirebaseQueryLiveData liveData = new 
   FirebaseQueryLiveData(POST_REF);
   @NonNull
   public LiveData<DataSnapshot> getDataSnapshotLiveData() {

return liveData;

}

【问题讨论】:

    标签: android firebase mvvm viewmodel android-livedata


    【解决方案1】:

    有不同的方法来为你的数据库建模来存档,遵循最佳实践总是好的,请参阅:https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure

    在这种情况下,由于您只需要个人资料图片和名称,我会将其直接保存到对象中:

        {
        "Posts":{
            "post1":
            {
                "likes":23,
                "userId":"id",
                "user":
                {
                    "imageUrl":"url", 
                    "name":"Name"
                }
            }
        }
    }
    

    当然,权衡是如果用户节点被更新,图像 URL 将不会被更新(除非你在云函数中编写代码来更新它)

    另一方面,您还可以对 Firebase 实时数据库执行这两个调用(一个用于获取帖子,另一个用于获取用户数据):

        ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get Post object and use the values to update the UI
            Post post = dataSnapshot.getValue(Post.class);
            ValueEventListener userListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot userDataSnapshot) {
                    post.setUser(userDataSnapshot.getValue(User.class);)
                }
            };
            mUserReference.addListenerForSingleValueEvent(userListener);//only fetch data once
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            // ...
        }
    };
    mPostReference.addValueEventListener(postListener);
    

    编辑:

    另一方面,由于您使用的是 FirebaseQueryLiveData https://firebase.googleblog.com/2017/12/using-android-architecture-components.html 并且可能希望避免编写那个帖子节点上的用户,我认为您可以同时拥有两个具有不同数据库引用的 ViewModel,一旦获取数据,您就可以更新帖子对象,例如post.setUser(user) 与用户从其他 ViewModel Observer 获得然后更新 UI。您还可以使用 HashMap 来跟踪哪些帖子需要哪些用户,尽管这个答案看起来像是一种方法:https://stackoverflow.com/a/46483213/1537389。希望有帮助

    【讨论】:

    • 我现在意识到你的问题是关于 LiveData with ViewModel 我会尝试更新帖子以匹配已建立的环境
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多