Setting Singleton property value in Firebase Listener

前端 未结 3 1947
挽巷
挽巷 2020-11-21 07:05

I\'m currently testing out Firebase along with a Singleton model I plan to use to access during the lifecycle of the whole app. I\'m now stuck with something that seems real

3条回答
  •  死守一世寂寞
    2020-11-21 07:42

    TL;DR: Embrace Firebase Asynchronicity

    As I mentioned in another post, you can deal with the asynchronous nature of Firebase using promises. It would be like this:

    public Task> synchronizeBookmarks(List bookmarks) {
         return Tasks.forResult(null)
            .then(new GetBook())
            .then(new AppendBookmark(bookmarks))
            .then(new LoadData())
    }
    
    public void synchronizeBookmarkWithListener() {
         synchronizeBookmarks()
             .addOnSuccessListener(this)
             .addOnFailureListener(this);
    }
    

    com.google.android.gms.tasks

    Google API for Android provides a task framework (just like Parse did with Bolts), which is similar to JavaScript promises concept.

    First you create a Task for downloading the bookmark from Firebase:

    class GetBook implements Continuation> {
    
        @Override
        public Task then(Task task) {
            TaskCompletionSource tcs = new TaskCompletionSource();
    
            Firebase db = new Firebase("url");
            Firebase bookmarksRef = db.child("//access correct child");
    
            bookmarksRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    tcs.setResult(dataSnapshot.getValue(Bookmark.class));
                }
            });
    
            tcs.getTask();
        }
    
    }
    

    Now that you got the idea, supose that setBookmarks and loadSampleData are also asynchronous. You also can create them as Continuation tasks (just like the previous one) that will run in sequence:

    class AppendBookmark(List bookmarks) implements
        Continuation, Task {
    
        final List bookmarks;
    
        LoadBookmarks(List bookmarks) {
            this.bookmark = bookmark;
        }
    
        @Override
        Task> then(Task task) {
            TaskCompletionSource> tcs = new TaskCompletionSource();
            bookmarks.add(task.getResult());         
            tcs.setResult(this.bookmarks);
            return tcs.getTask();
        }
    }
    
    class LoadSampleData implements Continuation, List> {
        @Override
        public Task> then(Task> task) {
            // ...
        }
    }
    

提交回复
热议问题