如何将这些Firebase ValueEventListeners重写为可读? [英] How do I rework these Firebase ValueEventListeners to be readable?

查看:127
本文介绍了如何将这些Firebase ValueEventListeners重写为可读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有什么我正在努力与如何编写与Firebase的异步调用良好的代码。以下是我的一个函数的代码,它从Firebase中检索所有用户和当前用户,并检查他们所选位置之间的距离。



我无法真正移动每个 ValueEventListeners 来分开函数,因为它们都必须连续触发。



如何让这段代码看起来不错?

  private void getUsersToDisplay(){
//获取用户从firebase显示
Log.w(TAG,User fetch initialized);

DatabaseReference currentUserRef = mDatabase.getReference()。child(users /+ mCurrentUser.getUid());

//从firebase获取当前用户
currentUserRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot currentUserSnapshot){
//获取用户在距离计算中选择的位置
final Double currentUserChosenLatitude =
Double.parseDouble(currentUserSnapshot.child(selected_location / latlng / latitude)。getValue()。toString());
final Double currentUserChosenLongitude =
Double.parseDouble(selected_location / latlng / longitude)。getValue()。toString());

DatabaseReference usersRef = mDatabase .getReference()。child(users);

//从firebase获取所有用户
usersRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSn apshot allUsersSnapshot){
//对于firebase中的所有用户
(DataSnapshot userSnap:allUsersSnapshot.getChildren()){
String userId = userSnap.getKey();

DatabaseReference userRef = mDatabase.getReference()。child(users /+ userId);

//如果用户不是当前用户
if(!userId.equals(mCurrentUser.getUid())){
//从firebase获取用户信息
userRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot userSnapshot){
Double userChosenLatitude =
Double.parseDouble(userSnapshot.child( selected_location / latlng / latitude)。getValue()。toString());
Double userChosenLongitude =
Double.parseDouble(userSnapshot.child(chosen_location / latlng / longitude)。getValue()。 toString());

float [] results = new float [1];
Location.distanceBetween(
currentUserChosenLatitude,
currentUserChosenLongitude,
userChosenLatitude,
userChosenLongitude,
results);

//如果用户在当前用户的10km范围内,则显示
if(results [0]< 10000){
users.put(userSnapshot.getKey ),(String)userSnapshot.child(first_name)。getValue());
mUserAdapter.add((String)userSnapshot.child(first_name)。getValue());
Log.w(TAG,用户显示抓取完成);


$ b @Override
public void onCancelled(DatabaseError databaseError){
Log.w(TAG,User to display fetch canceled) ;
}
});


Log.w(TAG,用户抓取完成);

$ b @Override
public void onCancelled(DatabaseError databaseError){
Log.w(TAG,用户取消取消);
}
});
Log.w(TAG,当前用户获取完成);

$ b @Override
public void onCancelled(DatabaseError databaseError){
Log.w(TAG,Current user fetch canceled);
}
});


解决方案

所以更容易阅读:

  onCreate(){
dataRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
doSomething(dataSnapshot);
...
}
...
}

$ b doSomething(DataSnapshot dataSnapshot){
...
}

如果我想让Firebase调用在另一个Firebase调用之后运行,我将它放在 doSomething 中。



但是,如果这个调用不需要依次运行(比如get current user和get all usercall from your sample code),我就这样做了:

 布尔firstCallDone = false; 
布尔值secondCallDone = false;

DataSnapshot firstDataSnapshot = null;
DataSnapshot secondDataSna pshot = null;

onCreate(){
firstRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
firstCallDone = true ;
firstDataSnapshot = dataSnapshot;
$ b $ if(firsCallDone& secondCallDone)
doSomething();
}
...
}
secondRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
secondCallDone = true;
secondDataSnapshot = dataSnapshot;

if(firsCallDone& secondCallDone)
doSomething();
}
...
}
}

doSomething(){
//用firstDataSnapshot和secondDataSnapshot做一些事情
...
}

希望如此帮助。


If there's something I'm struggling with it's how to write good looking code with asynchronous calls to Firebase. Below is the code for one of my functions that retrieves all users and the current user from Firebase and checks the distance between their chosen locations.

I can't really move each of the ValueEventListeners to separate functions since they all have to fire in succession.

How do I make this code look good?

private void getUsersToDisplay() {
    // Get users to display from firebase
    Log.w(TAG, "User fetch initialized");

    DatabaseReference currentUserRef = mDatabase.getReference().child("users/" + mCurrentUser.getUid());

    // Get current user from firebase
    currentUserRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot currentUserSnapshot) {
            // Get the users chosen location for use in distance calculation
            final Double currentUserChosenLatitude =
                    Double.parseDouble(currentUserSnapshot.child("chosen_location/latlng/latitude").getValue().toString());
            final Double currentUserChosenLongitude =
                    Double.parseDouble(currentUserSnapshot.child("chosen_location/latlng/longitude").getValue().toString());

            DatabaseReference usersRef = mDatabase.getReference().child("users");

            // Get all users from firebase
            usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot allUsersSnapshot) {
                    // For all users in firebase
                    for (DataSnapshot userSnap : allUsersSnapshot.getChildren()) {
                        String userId = userSnap.getKey();

                        DatabaseReference userRef = mDatabase.getReference().child("users/" + userId);

                        // If the user isn't the current user
                        if (!userId.equals(mCurrentUser.getUid())) {
                            // Get the user's info from firebase
                            userRef.addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot userSnapshot) {
                                    Double userChosenLatitude =
                                            Double.parseDouble(userSnapshot.child("chosen_location/latlng/latitude").getValue().toString());
                                    Double userChosenLongitude =
                                            Double.parseDouble(userSnapshot.child("chosen_location/latlng/longitude").getValue().toString());

                                    float[] results = new float[1];
                                    Location.distanceBetween(
                                            currentUserChosenLatitude,
                                            currentUserChosenLongitude,
                                            userChosenLatitude,
                                            userChosenLongitude,
                                            results);

                                    // If the user is within 10km of the current user, display it
                                    if (results[0] < 10000) {
                                        users.put(userSnapshot.getKey(), (String) userSnapshot.child("first_name").getValue());
                                        mUserAdapter.add((String) userSnapshot.child("first_name").getValue());
                                        Log.w(TAG, "User to display fetch complete");
                                    }
                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {
                                    Log.w(TAG, "User to display fetch cancelled");
                                }
                            });
                        }
                    }
                    Log.w(TAG, "Users fetch completed");
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "Users fetch cancelled");
                }
            });
            Log.w(TAG, "Current user fetch complete");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "Current user fetch cancelled");
        }
    });
}

解决方案

I write my code like this so it easier to read:

onCreate() {
    dataRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            doSomething(dataSnapshot);
            ...
        }
        ...
    }
}

doSomething(DataSnapshot dataSnapshot) {
    ...
}

If I want a Firebase call to run after another Firebase call, I place it inside doSomething.

BUT, if that call doesn't have to run after each other (like "get current user" and "get all user" call from your sample code), I made it like this:

boolean firstCallDone = false;
boolean secondCallDone = false;

DataSnapshot firstDataSnapshot = null;
DataSnapshot secondDataSnapshot = null;

onCreate() {
    firstRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            firstCallDone = true;
            firstDataSnapshot = dataSnapshot;

            if (firsCallDone && secondCallDone)
                doSomething();
        }
        ...
    }
    secondRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            secondCallDone = true;
            secondDataSnapshot = dataSnapshot;

            if (firsCallDone && secondCallDone)
                doSomething();
        }
        ...
    }
}

doSomething() {
    // do something with firstDataSnapshot and secondDataSnapshot
    ...
}

Hope this help.

这篇关于如何将这些Firebase ValueEventListeners重写为可读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆