How to return a DocumentSnapShot as a result of a method?

后端 未结 2 895
孤街浪徒
孤街浪徒 2020-11-21 04:36

A custom object that takes a parameter of (DocumentSnapShot documentsnapShot). also is an inner object from Firebase that retrieves a snapshot and set the values to my custo

2条回答
  •  别那么骄傲
    2020-11-21 05:38

    Use LiveData as return type and observe the changes of it's value to execute desired operation.

    private MutableLiveData userSettingsMutableLiveData = new MutableLiveData<>();
    
    public MutableLiveData getUserSettings(DocumentSnapshot documentSnapshot){
    
        DocumentReference mSettings = mFirebaseFirestore.collection("user_account_settings").document(userID);
        mSettings.get().addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                UserAccountSettings settings = documentSnapshot.toObject(UserAccountSettings.class);
                settings.setDisplay_name(documentSnapshot.getString("display_name"));
                settings.setUsername(documentSnapshot.getString("username"));
                settings.setWebsite(documentSnapshot.getString("website"));
                settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
                settings.setPosts(documentSnapshot.getLong("posts"));
                settings.setFollowers(documentSnapshot.getLong("followers"));
                settings.setFollowing(documentSnapshot.getLong("following"));
    
                userSettingsMutableLiveData.setValue(settings);
            }
        });
    
        return userSettingsMutableLiveData;
    }
    

    Then from your Activity/Fragment observe the LiveData and inside onChanged do your desired operation.

    getUserSettings().observe(this, new Observer() {
        @Override
        public void onChanged(UserAccountSettings userAccountSettings) {
            //here, do whatever you want on `userAccountSettings`
        }
    });
    

提交回复
热议问题