Android - Return boolean value relative Firebase

后端 未结 1 978
余生分开走
余生分开走 2021-01-22 21:11
public boolean checkGold(final int gold){
    mRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnaps         


        
1条回答
  •  有刺的猬
    2021-01-22 21:45

    Firebase Database is asyncronous, and its flow is outside the regular flow that we usually do. In this post, I tried to explain that (just for information)

    And in this case, you do something like this, right?

    boolean iWantValue = checkGold(10);
    if (iWantValue) {
        // do someting
    } else {
        // do something else
    }
    ...
    public boolean checkGold(final int gold) {
        ... // content here are still the same as mentioned in question
    }
    

    But if we know it is asyncronous, it should be like this:

    int currentGold = 0; // place gold here so it can be accessed anywhere
    ...
    // wherever you want to check gold, type this
    currentGold = 10; // update this value first, right?
    checkGold();
    ...
    public void checkGold() {
        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                goldparse = Integer.parseInt(value);
                if (currentGold > goldparse){
                    // do something
                } else {
                    // do something here
                }
            }
            ...
        });
    }
    

    Or if you are like me who want something tidy:

    public void checkGold() {
        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                doSomethingOrNot(Integer.parseInt(dataSnapshot.getValue(String.class)));
            }
            ...
        });
    }
    
    private void doSomethingOrNot(int goldparse) {
        if (currentGold > goldparse){
            // do something
        } else {
            // do something here
        }
    }
    

    It needs time to be familiar with this, but it's worth it. Hope this helps

    0 讨论(0)
提交回复
热议问题