LoginSignup
86
85

More than 5 years have passed since last update.

Otto を使って快適 pub/sub 生活

Posted at

Otto って

色々なライブラリをオープンソースとしてくれている square による event bus 用のライブラリです。

Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently.

(from 公式)

event bus って

レイヤーの上から下のモジュールを呼ぶ場合は、素直にメソッドをコールすることで実現できます。
ですが、反対向きの場合だとコールバックを用意したりで色々面倒ですよね。
その問題を解決するための仕組みです。

具体的には pub/sub をクラスベースでシンプルに書けるような感じ。

従来の書き方

  • android.graphics.Point を publish したい場合

publish side

void doPublish(Context context, Point point) {
    Intent intent = new Intent(SubscribeFragment. ACTION_POINT_PUBLISH).
        putExtra("x", p.x).
        putExtra("y", p.y);

    context.sendBroadcast(intent);
}

subscribe side

SubscribeFragment.java
static final String ACTION_POINT_PUBLISH = "some.unique.string";

BroadcastReceiver mValueReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Point point = new Point();
        point.x = intent.getIntExtra("x", 0);
        point.y = intent.getIntExtra("y", 0);

        receiveValue(point);
    }
};

void receiveValue(Point point) {
    // do stuff
}

@Override
public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter(ACTION_VALUE_PUBLISH);
    getActivity().registerReceiver(mValueReceiver, filter);
}

@Override
public void onPause() {
    getActivity().unregisterReceiver(mValueReceiver);

    super.onPause();
}

所感

  • わざわざ Intent に入れたり出したりするのとかイケてない
  • めんどい
    • Broadcast したい対象が複数になったりすると、さらにめんどい

Otto を使うと

publish side

void doPublish(Context context, Point point) {
    BusHolder.get().post(point);
}

subscribe side

SubscribeFragment.java
@Subscribe
void receiveValue(Point point) {
    // do stuff
}

@Override
public void onResume() {
    super.onResume();

    BusHolder.get().register(this);
}

@Override
public void onPause() {
    BusHolder.get().unregister(this);

    super.onPause();
}

singleton

BusHolder.java
class BusHolder {
    static Bus mBus = new Bus();

    static Bus get() {
        return mBus;
    }
}

所感

  • アノテーション付けるだけで良いのが素敵
  • 自作クラスだろうとフレームワークのクラスだろうと気にせず post すれば (大体) おっけー
  • 複数クラスを subscribe する場合はメソッドを増やすだけでよい (!!)

and more

  • Otto は guava の EventBus を fork して Android に最適化してある
  • greenDAO などで有名な greenbot さんも独自実装の event bus を 公開 してくれています
86
85
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
86
85