【问题标题】:Is this the right way to use queries in the Firestore from Android Jetpack ViewModel?这是在 Android Jetpack ViewModel 的 Firestore 中使用查询的正确方法吗?
【发布时间】:2023-04-11 09:40:01
【问题描述】:

我在android studio中开发一个应用,除了使用MVVM外,还使用“导航组件架构”,为此,在fragment的ViewModels中查询Firestore是否正确?

public class ProfileViewModel extends ViewModel {

    private MutableLiveData<String> name;
    private MutableLiveData<String> lastName;


    public ProfileViewModel() {
        name= new MutableLiveData<>();
        lastName= new MutableLiveData<>();

    }

    public void saveToFirestore(){
        FirebaseFirestore db  =FirebaseFirestore.getInstance();
        db.document( PATH )
                .set( OBJECT )
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                    }
                });

    }

}

【问题讨论】:

  • 从 Java 的角度来看,你可以看看另一个 approach,它是这个 article 的一个 repo。您将能够看到如何使 LiveData 与 ViewModel 和 Repository 一起工作。
  • @AlexMamo 您提供的示例有很多错误。
  • @Pooja 我会重新检查一下。
  • @AlexMamo 你还回复了某人说你会在两个月前 ????
  • @Pooja 我需要找点时间 ;)

标签: java android firebase google-cloud-firestore


【解决方案1】:

严格来说,在 ViewModel 中进行数据库查询是不正确的。 ViewModel 应该为实际的数据库查询查询“存储库”类型的对象。 ViewModel 负责将那里的对象转换为适合 View 交互的对象。

您可能想看看我的示例项目,该项目使用 MVVM 和 Firestore,使用 Jetpack 组件。它不包含任何写入数据的示例,但该模式认为 ViewModel 不知道数据存储实现细节。

https://github.com/CodingDoug/firebase-jetpack

【讨论】:

  • 嗨,Doug,感谢您提供代码和 Youtube 演示文稿。这是一个非常重要的话题。从那时起,对于 MVVM 实施的 firebase 建议是否有任何变化?是否有计划制定更通用的解决方案?因为维护起来似乎很复杂,特别是对于较小的项目。谢谢。
  • @DougStevenson 这个 github 存储库在 Java 中可用吗?
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 2015-09-11
  • 2012-05-11
  • 2018-12-31
  • 2021-04-29
  • 1970-01-01
相关资源
最近更新 更多