如何合并来自不同回调的2个列表?

时间:2018-09-18 17:36:38

标签: java merge callback

我有两种方法使用的回调,用于从“实时数据库”中获取喜欢和访问的数据。

 public interface ActionCallback {

        void setActionList(List<ActionModel> actionModels);

    }

每个方法都有ActionCallback类型的回调作为方法参数。

private void getLikes(ActionCallback callback){
        realtimeReference.child("Likes").child(getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<ActionModel> actionModels = new ArrayList<>();
                for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                    actionModels.add(new ActionModel(
                            Long.valueOf(snapshot.child("timestamp").getValue().toString()),
                            snapshot.getKey(),
                            "likes"));
                }
                callback.setActionList(actionModels);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        });
    }

    private void getVisits(ActionCallback callback){
        realtimeReference.child("Visits").child(getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<ActionModel> actionModels = new ArrayList<>();
                for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Long timestamp = Long.valueOf(snapshot.child("timestamp").getValue().toString());
                    String fromUid = snapshot.child("fromUid").getValue().toString();
                    actionModels.add(new ActionModel(timestamp, fromUid, "visits"));
                }
                callback.setActionList(actionModels);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        });
    }

我需要在getSortedList()方法中从他们的回调中合并列表,我尝试这样做,但是它对我不起作用,我只收到getLikes()列表。

 public void getMergedActions(ActionCallback callback){
        List<ActionModel> actionModels = new ArrayList<>();
        getLikes(actionLikeModels -> {
            actionModels.addAll(actionLikeModels);
            getVisits(actionVisitModels -> actionModels.addAll(actionVisitModels));
            Collections.sort(actionModels, (e1, e2) -> Long.compare(e1.getTimestamp(), e2.getTimestamp()));
            callback.setActionList(actionModels);
        });
    }

0 个答案:

没有答案