使用 MVVM 架构从 FireStore 检索数据

Ray*_*yen 3 java android mvvm firebase google-cloud-firestore

我正在尝试遵循 Android 架构原则,并希望您在我的 FireStore 数据库之上实施它们。

目前我有一个存储库Class来处理我所有的底层数据查询。我有一个Fragment需要Set<String>来自文档中字段的键,我想知道检索这些数据的最佳方法是什么。在我之前的问题中, Alex Mamo建议将 anInterface与 an 结合使用,onCompleteListener因为从 Firestore 检索数据是Asynchronous.

这种方法似乎有效,但我不确定如何从中提取数据Interface到我的Fragment. 如果我希望使用这些数据,我的代码是否必须在我对abstract方法的定义范围内?

如果要将数据从 Firestore 获取到我的Fragment我必须将InterfaceFragment 中定义的对象作为参数传递给我的存储库,我是否仍然遵循 MVVM 原则?

这是使用存储库查询 Firestore 数据库的推荐方法吗?

下面是我Interface调用 aViewModel来检索数据的方法:

public interface FirestoreCallBack{
    void onCallBack(Set<String> keySet);
}

public void testMethod(){
    Log.i(TAG,"Inside testMethod.");
    mData.getGroups(new FirestoreCallBack() {
    //Do I have to define what I want to use the data for here (e.g. display the contents of the set in a textview)?
        @Override
        public void onCallBack(Set<String> keySet) {
            Log.i(TAG,"Inside testMethod of our Fragment and retrieved: " + keySet);
            myKeySet = keySet;
            Toast.makeText(getContext(),"Retrieved from interface: "+ myKeySet,Toast.LENGTH_SHORT).show();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

ViewModel调用存储库的方法:

private FirebaseRepository mRepository;
public void getGroups(TestGroupGetFragment.FirestoreCallBack firestoreCallBack){
    Log.i(TAG,"Inside getGroups method of FirebaseUserViewModel");
    mRepository.getGroups(firestoreCallBack);
}
Run Code Online (Sandbox Code Playgroud)

最后我的 Repository 方法到query我的 FireStore 数据库:

public void getGroups(final TestGroupGetFragment.FirestoreCallBack firestoreCallBack){
    Log.i(TAG,"Attempting to retrieve a user's groups.");
    userCollection.document(currentUser.getUid()).get().addOnCompleteListener(
            new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()){
                        DocumentSnapshot document = task.getResult();
                        Log.i(TAG,"Success inside the onComplete method of our document .get() and retrieved: "+ document.getData().keySet());
                        firestoreCallBack.onCallBack(document.getData().keySet());
                    } else {
                        Log.d(TAG,"The .get() failed for document: " + currentUser.getUid(), task.getException());
                    }
                }
            });
    Log.i(TAG, "Added onCompleteListener to our document.");
}
Run Code Online (Sandbox Code Playgroud)

已编辑

public void testMethod(){
    Log.i(TAG,"Inside testMethod.");
    mData.getGroups(new FirestoreCallBack() {
        @Override
        public void onCallBack(Set<String> keySet) {
            Log.i(TAG,"Inside testMethod of our Fragment and retrieved: " + keySet);
            myKeySet = keySet;
            someOtherMethod(myKeySet); //I know I can simply pass keySet.
            Toast.makeText(getContext(),"GOT THESE FOR YOU: "+ myKeySet,Toast.LENGTH_SHORT).show();
        }
    });

    Log.i(TAG,"In testMethod, retrieving the keySet returned: "+ myKeySet);
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*ira 8

例如,interface我不是只用于LiveData将数据带到回收站视图中。

首先,我们必须创建我们的Firestore query. 在这个例子中,我列出了一个集合中的所有文档。

public class FirestoreLiveData<T> extends LiveData<T> {

    public static final String TAG = "debinf firestore";

    private ListenerRegistration registration;

    private CollectionReference colRef;
    private Class clazz;

    public FirestoreLiveData(CollectionReference colRef, Class clazz) {
        this.colRef = colRef;
        this.clazz = clazz;
    }


    EventListener<QuerySnapshot> eventListener = new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
            if (e != null) {
                Log.i(TAG, "Listen failed.", e);
                return;
            }


            if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
                List<T> itemList = new ArrayList<>();
                for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {
                    T item = (T) snapshot.toObject(clazz);
                    itemList.add(item);
                    Log.i(TAG, "snapshot is "+snapshot.getId());
                }
                setValue((T) itemList);
            }
        }
    };

    @Override
    protected void onActive() {
        super.onActive();
        registration = colRef.addSnapshotListener(eventListener);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if (!hasActiveObservers()) {
            registration.remove();
            registration = null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,我们在我们的链接中创建一个链接 Repository

public class Repository {

    public Repository() {
    }

    public LiveData<List<ProductsObject>> productListening(GroupObject group) {
        return new FirestoreLiveData<>(DatabaseRouter.getCollectionRef(group.getGroupCreator()).document(group.getGroupKey()).collection("ProductList"), ProductsObject.class);
    }

}
Run Code Online (Sandbox Code Playgroud)

之后,我们创建我们的ViewModel

public class MyViewModel extends ViewModel {

    Repository repository = new Repository();

    public LiveData<List<ProductsObject>> getProductList(GroupObject groupObject) {
        return repository.productListening(groupObject);
    }

}
Run Code Online (Sandbox Code Playgroud)

最后,在我们MainActivityFragment我们观察 ou Firestore 中包含的数据:

    viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    viewModel.getProductList(groupObject).observe(this, new Observer<List<ProductsObject>>() {
        @Override
        public void onChanged(@Nullable List<ProductsObject> productsObjects) {
            //Log.i(TAG, "viewModel: productsObjects is "+productsObjects.get(0).getCode());
            adapter.submitList(productsObjects);
        }
    });
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助。