【问题标题】:Can I put Firebase ValueEvent listener in Application class我可以将 Firebase ValueEvent 侦听器放在 Application 类中吗
【发布时间】:2018-02-08 11:05:51
【问题描述】:

我想在 5 个活动中使用 Firebase Value 事件监听器。并且所有的监听器都会做同样的工作,那么我可以将监听器放在应用程序类中并在应用程序终止时移除监听器吗?

public class MyApplication extends Application {

    private RefWatcher refWatcher;
    private ValueEventListener value_event_listener;

    public static RefWatcher getRefWatcher(Context context) {
        MyApplication application = (MyApplication) context.getApplicationContext();
        return application.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
        EmojiManager.install(new IosEmojiProvider());

        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        refWatcher = LeakCanary.install(this);

        value_event_listener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
          //TODO
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                //TODO

            }
        };
        FirebaseDatabase.getInstance().getReference().child(C.DELIVERY).addValueEventListener(value_event_listener);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        FirebaseDatabase.getInstance().getReference().child(C.DELIVERY).removeEventListener(value_event_listener);
    }


}

【问题讨论】:

    标签: android firebase firebase-realtime-database


    【解决方案1】:

    简短的回答,是的,但是有一种更简洁的方法来处理它。

    SOLID 的方法是创建一个实用程序类,该类从您要侦听此事件的每个位置调用。通过这种方式,如果您的需求将来发生变化,您可以扩展实用程序类。然后可以应用更改,而不会影响使用它的所有位置。

    这也使这更易于测试,因为您可以模拟实用程序类来验证不同的场景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      相关资源
      最近更新 更多