firebase 在Tasks.whenAllSuccess()(Firerestore)中将多个任务列表的结果转换为它们的POJO

6jjcrrmo  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(66)
List<Task<DocumentSnapshot>> fetchUserTasks = new ArrayList<>();

List<Task<DocumentSnapshot>> fetchLikeTasks = new ArrayList<>();

字符串
我创建了两个任务列表。如果它是一个任务列表,我可以将object转换为DocumentSnapshot并存储在POJO中,如下所示:

Task combineUserTasks =  Tasks.whenAllSuccess(fetchUserTasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
                    @Override
                    public void onSuccess(List<Object> objects) {

                        for (Object object : objects) {

                            UserModel userModel = ((DocumentSnapshot) object).toObject(UserModel.class);

                            userModelArrayList.add(userModel);

                        }

                });


但在两个任务列表的情况下,我如何可以投结果为每个列表?

Tasks.whenAllSuccess(combineUserTasks, combineLikeTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
                    @Override
                    public void onSuccess(List<Object> objects) {

                        // How to fetch/cast data for individual POJO here?

                    }
                });

更新1:

Tasks.whenAllSuccess(combineUserTasks, combineLikeTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
                    @Override
                    public void onSuccess(List<Object> objects) {

                        for (Object object : objects) {

                            UserModel userModel = ((DocumentSnapshot) object).toObject(UserModel.class);

                            LikeModel likeModel = ((DocumentSnapshot) object).toObject(LikeModel.class);

                            userModelArrayList.add(userModel);

                            likeModelArrayList.add(likeModel);

                        }

                    }
                });

nbewdwxp

nbewdwxp1#

据我所知,你有两种类型的列表,userModelArrayList是UserModel类型,likeModelArrayList是LikeModel类型。为了能够将每个对象添加到其相应类型的列表中,您应该创建类型为UserModel和LikeModel的Task对象列表。所以请更改以下代码行:

List<Task<DocumentSnapshot>> fetchUserTasks = new ArrayList<>();
List<Task<DocumentSnapshot>> fetchLikeTasks = new ArrayList<>();

字符串

List<Task<UserModel>> fetchUserTasks = new ArrayList<>();
List<Task<LikeModel>> fetchLikeTasks = new ArrayList<>();


因此,不要添加DocumentSnapshot对象,而是添加实际的对象。所以之前使用toObject()。也就是说,您可以使用instanceof操作符检查每个对象类型,如以下代码行所示:

Tasks.whenAllSuccess(combineUserTasks, combineLikeTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> objects) {
        for (Object object : objects) {
            if (object instanceof UserModel) {
                userModelArrayList.add(userModel);
            } else if (object instanceof LikeModel) {
                likeModelArrayList.add(likeModel);
            }
        }
    }
});


现在,您将用相应的对象类型填充每个列表。

相关问题