Coder Social home page Coder Social logo

otto's Introduction

Otto - An event bus by Square

An enhanced Guava-based event bus with emphasis on Android support.

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

Forked from Guava, Otto adds unique functionality to an already refined event bus as well as specializing it to the Android platform.

For usage instructions please see the website.

Deprecated!

This project is deprecated in favor of RxJava and RxAndroid. These projects permit the same event-driven programming model as Otto, but they’re more capable and offer better control of threading.

If you’re looking for guidance on migrating from Otto to Rx, this post is a good start.

Download

Downloadable .jars can be found on the GitHub download page.

You can also depend on the .jar through Maven:

<dependency>
  <groupId>com.squareup</groupId>
  <artifactId>otto</artifactId>
  <version>1.3.8</version>
</dependency>

or Gradle:

implementation 'com.squareup:otto:1.3.8'

Snapshots of the development version are available in Sonatype's snapshots repository.

License

Copyright 2012 Square, Inc.
Copyright 2010 Google, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

otto's People

Contributors

adennie avatar ardacebi avatar cushon avatar eburke avatar edenman avatar holmes avatar imminent avatar jakewharton avatar joeykrim avatar johncarl81 avatar kevinsawicki avatar kryali avatar loganj avatar matthewmichihara avatar mbarany avatar nicholassm avatar npombourcq avatar pforhan avatar pyricau avatar rjrjr avatar romansky avatar swankjesse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

otto's Issues

Include instructions regarding ProGuard?

Hi,

First of all: Thanks for a great library.

I think it would be a good idea to include a note about ProGuard configuration needed for Otto to work in an app:
-keep class ** { @com.squareup.otto.Subscribe public *; }

Otherwise the callback methods are removed by ProGuard. Would you like a pull-request for this?

Best regards,
Nicholas

Manual subscribe for base classes

I would like to subscribe to events in my base class but this does not seem to be possible. The docs explain this is for performance reasons, would there be a way to do a manual subscription for this case?

Would you consider adding this feature?

NoSuchMethodException when registering class instances on Android 2.2 & 2.3.7

Each and every time I try to register a class instance as a listener on OS versions older than Honeycomb, my app throws a NoSuchMethodException. I know that on the site it's stated that the library "is compatible with all versions of Android and has no minimum SDK requirement.", but this probably has to do something with that, since it runs perfectly on Honeycomb, ICS & Jelly Bean.

Code:

@Override
public void onResume() {
        super.onResume();
        EventBusProvider.getInstance().register(this);
}

Log:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {com.app/com.uilibrary.HomeActivity}: java.lang.NoSuchMethodException
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2241)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2256)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1789)
    at android.app.ActivityThread.access$1500(ActivityThread.java:123)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3835)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NoSuchMethodException
    at java.lang.Class.getDeclaredMethods(Native Method)
    at java.lang.ClassCache.getDeclaredMethods(ClassCache.java:140)
    at java.lang.Class.getDeclaredMethods(Class.java:757)
    at com.squareup.otto.AnnotatedHandlerFinder.loadAnnotatedMethods(AnnotatedHandlerFinder.java:52)
    at com.squareup.otto.AnnotatedHandlerFinder.findAllProducers(AnnotatedHandlerFinder.java:116)
    at com.squareup.otto.HandlerFinder$1.findAllProducers(HandlerFinder.java:33)
    at com.squareup.otto.Bus.register(Bus.java:187)
    at com.uilibrary.HomeActivity.onResume(HomeActivity.java:218)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
    at android.app.Activity.performResume(Activity.java:3832)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2231)
    ... 12 more

Problem using it with AndroidAnnotations

I tried using dagger with AndroidAnnotations within activities.
The problem is that AndroidAnnotations creates a subclass of my activity.
When you look for annotated subscribers in com.squareup.otto.AnnotatedHandlerFinder#loadAnnotatedMethods you use listenerClass.getDeclaredMethods()
This does not return the methods from the super-class. So I can not receive messages if I create a subclass of the class that contains subscribe methods.
I got around this by registering an anonymous class with an annotated method.
Not sure if you want to support this, just mentioned it.
Thanks,
Gabi

Search superclasses as option?

We don't want to search superclasses for @subscribe and @produce by default, but would you consider an option to enable this?

Without this ability, AndroidAnnotations-processed classes can't be used. Suppose I create a class MyClass.java that uses some of AndroidAnnotations's features. AndroidAnnotations will generate MyClass_.java whose class derives from MyClass and use that as the instantiated type. My logic (and @Produce/@subscribe methods) live in its superclass, MyClass.

Controlling which threads the event gets posted to

Currently, Otto enforces the Thread level restrictions on the entire bus. But let's say if I want to post my events from a different thread to a different thread, is there support for that?

Currently I am overriding the post method of the Bus to make sure all events are posted on the main thread. This lets my background threads also use the same bus with the guarantee that events shall be posted to the main thread. Are there any potential issues there? Or is there some built-in support for this?

Oh I just read #72 and I agree on Otto's approach but will there be any repercussions if I subclass Bus.post and use a Thread-Aware implementation to fire events only on the main thread. Sometimes the Network response will attempt to update the UI by firing an Event which can only be on the main thread.

Producers only called for subscribers to exact type, not any assignable type

This is possibly by design, but I couldn't find it documented anywhere, so I thought I'd raise it anyway.

When subscribe() is called, any producers will be called only if there are subscribers to the exact type that the producer returns, not supertypes, interfaces, etc.

This is distinct from the behaviour when post() is called, when subscribers to any "assignable" type will be called.

E.g.

class A {
    @Produce public SubType produceSomeType() {
        return new SubType();
    }

    @Subscribe public void onSuperType(SuperType event) {
        // Do something with event
    }

    A() {
        getBus().register(this);
    }
}

class SuperType {}
class SubType extends SuperType {}

When A registers, produceSubType() will not be called, hence neither will onSuperType() , but if a SubType is posted to the bus, onSuperType() will receive it.

I really only opened this issue to find out if this is by design or not, and if so to suggest that it should be documented somewhere other than the code.

OTTO swallowing exceptions

If a method called in the user's code while dispatching an Event throws an exception, OTTO swallows it, and re-throws it's own cryptic exception, completely occluding the original Exception. This makes debugging difficult.

at com.squareup.otto.Bus.throwRuntimeException(Bus.java:456)
at com.squareup.otto.Bus.dispatch(Bus.java:386)
at com.squareup.otto.Bus.dispatchProducerResultToHandler(Bus.java:252)

If it still caught and re-threw it's own Exception, but at least included some information about the original exception (maybe in the Cause field), that would be extremely helpful.

Feature suggestion: add ordered broadcast equivalent

A fairly clean pattern for a service to either update the foreground UI or raise a Notification is to use an ordered broadcast. It'd be nice to have an in-process-only equivalent of this, and LocalBroadcastManager doesn't do ordered broadcasts.

Have you considered a variation on an Otto event that works like ordered broadcasts? For example, priority could be specified as part of the @Subscribe annotation, and bus.abort() or something could be the abortBroadcast() equivalent. Or, just handle the prioritization within Otto, and have Otto users handle aborting themselves (e.g., boolean flag in the event object to indicate that the event was consumed, so lower-priority subscribers could know to skip processing).

Anyway, just a thought...

It's terrible to define lots of Custom events when post and subcribe

I am Confused whether make use of eventbus to reconstruction my code,
cause eventbus must define lots of events(Custom events),each action should have relevant event.

I think it's terrible。

i changed the event bus to a message bus。
i post a standard Message(eg Event) to the bus, and according to it's filter to tell all subscribers which is alive who can accept . this will produce less Custom Event

public class Event{
public Set filter; // value is subscriber.getClass().getName()
// + this.getClass().getName()
public Object msg;

  public void addFillter(String subscriberClassName){
           if(null == filter){
           filter = new HashSet<String> ();
           }
           filter.add(subscriberClassName);
  }

}

Is there any Better Design
or what's the problem of my Design

the detail discuss ,you can visit greenrobot/EventBus#86

Is it a bug ???

Hi,

I just noticed a strange thing.

I have a service which execute a certain task on a dedicated thread.

I use Otto to display the advancement on the screen. So the service posts an object on the event bus for each percent accomplished.

To be sure I get the last update even if the screen is off (and so the activity onPause) I added a producer to the service:

    @Produce
    public ExecFragmentDialog.UpdateExecutor updateScreenWhenNoMoreDataReceived(){
        return messageToSendOnScreen;
    }

Since I added the producer I got a crash each time I launched the Producer:

Producer method for type MY_CLASS already registered

And the issue is that I registered the service only ONE TIME. I am sure of that (not difficult to check).
And the service is unregistered in onDestroy.

Even more strange is that if I remove the register(this) in the onStart() method of the service... it works!!!

This way of doing is not described in the documentation:


Producers, like subscribers, must also be registered:

bus.register(this);

I think it s a bug, but may be I have not understood something.

Michaël

Documentation does not define `bus`

The documentation assumes the existence of a variable named bus without indicating what class it is, how you create one, etc.

Specifically:

These examples assume you have an instance in the variable bus obtained through injection or another appropriate mechanism.

An instance of... what?

Android: Classes that register with Bus cannot safely use private methods with newer API parameters.

Android apps that safely use new API classes as parameters in a method will still crash due to the following line in AnnotatedMethodHandler:

for (Method method : listenerClass.getDeclaredMethods())

An example set of methods:

@TargetApi(19)
private void doANewThingIfPossible() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
         CaptioningManager captioningManager = (CaptioningManager) getActivity().getSystemService(Context.CAPTIONING_SERVICE);
         doANewThingWithCaptioning(captioningManager);
    }

@TargetApi(19)
private void doANewThingWithCaptioning(CaptioningManager mgr) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // Do something with captioning
    }
}

A class with these methods is safe to run on an older device without Otto, but attempting to register this class to an Otto Bus will cause the class to crash with a java.lang.NoClassDefFoundError: android/view/accessibility/CaptioningManager upon registration.

There are definitely work-arounds and good coding practices that will prevent this, like inlining or moving doANewThingWithCaptioning to a new class, but wanted to bring it up as adding Otto to a pre-existing class can cause this to crop up.

Real stacktrace is cut off

When my subscriber method fails with an exception, otto is being nice enough to tell me, the problem is the RuntimeException that otto throws take up too much of the log buffer and the real exception is cut off. See the last line of this exception.

Any ideas on how to get the nested exception? It is really hard to debug without that cut off stack trace.

03-06 14:03:47.845: E/AndroidRuntime(18056): FATAL EXCEPTION: main
03-06 14:03:47.845: E/AndroidRuntime(18056): Process: my.obfuscated.package, PID: 18056
03-06 14:03:47.845: E/AndroidRuntime(18056): java.lang.RuntimeException: Could not dispatch event: class my.obfuscated.package.bus.LayoutFragmentPush to handler [EventHandler public void my.obfuscated.package.activity.MainActivity.onEvent(my.obfuscated.package.bus.LayoutFragmentPush)]
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.squareup.otto.Bus.throwRuntimeException(Bus.java:456)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.squareup.otto.Bus.dispatch(Bus.java:386)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.squareup.otto.Bus.dispatchQueuedEvents(Bus.java:367)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.squareup.otto.Bus.post(Bus.java:336)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at my.obfuscated.package.bus.MainThreadBus.post(MainThreadBus.java:40)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at my.obfuscated.package.widget.CLinkButton.onClick(CLinkButton.java:187)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at my.obfuscated.package.widget.ICButton.onTouchEvent(ICButton.java:112)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.View.dispatchTouchEvent(View.java:7706)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2238)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2068)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1515)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.app.Activity.dispatchTouchEvent(Activity.java:2458)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2016)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.View.dispatchPointerEvent(View.java:7886)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3954)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3833)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3525)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3582)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5602)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5582)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5553)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5682)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.os.MessageQueue.nativePollOnce(Native Method)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.os.MessageQueue.next(MessageQueue.java:138)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.os.Looper.loop(Looper.java:123)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at java.lang.reflect.Method.invokeNative(Native Method)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at java.lang.reflect.Method.invoke(Method.java:515)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-06 14:03:47.845: E/AndroidRuntime(18056):    at dalvik.system.NativeStart.main(Native Method)
03-06 14:03:47.845: E/AndroidRuntime(18056): Caused by: android.view.InflateException: Binar

Caching most recent events

Hey, I'm currently using Greenrobot's EventBus but I'd like to move to Otto because of its coming integration with AndroidAnnotation.
So far I'm loving it but it seems that it doesn't support the caching of the most recent events. Using EventBus they're called "Sticky events".
Are you planning to add that feature?

Thanks

Generic producers

Hey,

I'm moving my app from EventBus to Otto, so far so good.
Concerning Producers, would it be doable to have something like this?

public class MyClass<T> {

    T lastEvent;

    @Produce
    public T produceEvent() {
        return lastEvent;
    }

}

I just tried and nothing is produced. I understand it might be hard to know the return type but I'd love to have generic producers.

Thanks

Posting instance of subclass calls subscribers of its superclass

Hi,
I noticed that when I post() an instance of subclass on the bus, the subscribers of its superclass are also invoked.
Also, there is an asymmetry between producing an instance of a subclass and of its superclass, which call exactly once their subscribers.

Here is a "test case": https://gist.github.com/venator85/5487144

Is this intended behaviour? While the producing behaviour is consistent with the sentence "Registering will only find methods on the immediate class type." on the web site, my understanding was that it would still hold for subscribers.
Thanks ;)

Count handlers

I am looking for a way to count number of subscribers for a specific event. The methods of Bus class have private fields and methods that its child class can't access. Because, my interest is "if anyone have received event?", currently I can't answer question, or is there a way to work around?

Cached events.

Can we have an option to cache events? The last event can be cached and the next time a subscriber registers itself, it will receive a copy of that cached event. We have the concept of producers but the developer has to maintain his own cache and provide the event to the producer. It would be fantastic if there were an option to automate this.

Compatibility with androidannotations

Hello,

We migrate from roboguice eventmanager to otto but we face an issue concerning the compatibility with android annotation (#15)
What we understand is that the branch code-gen is compatible with AA ? If yes, when will you merge it to master ?

Many listeners on same event, having unique id's

I'm using Otto for my app which uses he download manager and some services around it.

I have some fragments and views on the same activity, more than one registered at a given time on DownloadFinishedEvent. Downloads have their (some sort of) unique id's, currently I'm adding a download_id field on event class and for each subscriber, I'm checking it against its download_id.

My question is, wouldn't it be a better solution, if we had

register(Object object, long id) and
post(Object object, long id)

and have only relevant subscribers get the call?

Do you think implementing such a use case makes sense and would it be really hard to achieve? I'm not an experienced developer but if you think it's that hard and it makes sense to have it as a feature, I would love to prepare a pull request for something like that :)

API extensions for 3rd party integration

I saw some development was happening recently on Otto to extend the API and want to support the direction it is heading. I wrote a very similar bus to Otto in my library Transfuse which takes a couple of lessons from the Otto playbook. Transfuse's EventManager is not quite as feature rich, however, and I would rather plug in Otto to incorporate these features than maintaining my own event bus implementation. In fact I would love to integrate Otto into my library.

What I need to integrate Otto into Transfuse is the following:

Generalize the EventHandler/EventProducer into interfaces so I may use my own library specific implementation.

Open up the following methods to manually register/unregister individual handers and producers in Otto:

void registerProducer(Class event, EventProducer producer)
void unregisterProducer(Class event)
void registerSubscriber(Class event, EventHandler handler)
void unresigerSubscriber(Class event, EvnetHandler handler)

It looks like the current direction is to make these methods package-private. This is completely acceptable and will allow the integration points I need but making these public would be more convenient. It is understandable to not make these public to keep the api noise low.

Thanks, and I hope to see these integration points in the 2.0.0 release.

Refreshing the screen (fragment) from another thread

Hi,
I am using Otto on my application. It works well.

I would be interested in refreshing the screen from an event in an intentservice (which has its own thread).

For that, I am trying to use Otto with ThreadEnforcer.ANY

But I got the same exception that I would obtain if I would call the view directly from the intentService (means other that the main thread). Is there a way in Otto to "redirect" easily the event from the IntentService to the Main thread ??? I just want to know when to do it.

Thank you

Michael

[Enhancement] register(CurrentClass.this) at current class level in the hierarchy

So I though this was built in by default but apparently not.

give two classes:

class One {

  create(){
    bus.register(One.this);
  }

  @Subscribe eventUpdate(Event event){
    //...
  }
  //...
class Two extends One 

  create(){
    bus.register(this);
  }

  @Subscribe eventUpdate(EventTwo event){
    //...
  }
  //...

When sending an Event, I would expect eventUpdate(Event ..) in class One to receive the event. As I have explicitly registered it at that class. Level, of course this does not happen.

I know that the implementation only searches the immediate class level, which to me makes sense at the level you register it at. Not just the top level.

I know its probably against the aim but would something like .register(One.class,this) be possible within the goal of the lib?

Make a simple Bus interface

interface Bus {
  public void post(Object event);
  public void register(Object subscriber);
  public void unregister(Object subscriber);
}

And rename the existing Bus class something like BasicBus.

Doing something like this makes it much easier for an app to wrap the real bus with value add features (like scoping and life cycle) without requiring clients to know anything tricky is going on.

Event subscription on Activity not fired on post from a Service in a different module.

Hi, I was trying to extract some of the code from my project into a module/library (a Service and some other classes), but when I try to notify an Activity of my main module (where the views resides) from my Service it seems like the bus is not finding the subscription to deliver the event.

I don't know if I misunderstood Otto's way of delivering events between threads, but I think the Service and the Activity are running on UI's thread, Service is receiving correctly the events posted from the Activity but not at the reverse case.

I think that the service residing in a different module (and package) than the Activity is the reason why I can't receive events on Activities, but I don't know why is happening.

Can someone please explain me the cause of this? Maybe it can be a bug.

otto proguard

Otto is a very good library. But when I passed Proguard packaged into APK, data thread transmission failure, I have to follow the instructions to
-keepclassmembers class * * {
@com.squareup.otto.Subscribe public *;
@com.squareup.otto.Produce public *;
}
Otto demo, the project is, click the button no reaction. Look forward to solve as soon as possible.

Override point dispatch, package protected

I suppose this is a nit, but Bus.dispatch is declared protected and is said to be an "appropriate override point", but EventHandler has package access. I could put my class at the squareup level, but that just seems funky. Can EventHandler be made public?

Various questions

I just learned about Otto--I use Guava's EventBus with RoboGuice extensively. First, I'm not sure where a good place is to ask questions like this.. A Google group might be excessive, and it seems too specialized for Stack Overflow.

It's not clear to me what the purpose is of the @Produce feature. I guess it's a convenience annotation that automatically posts the return value at registration time? If my understanding is correct, consider changing the documentation to call this out explicitly? I didn't understand it until writing this question and re-parsing it several times.

ThreadEnforcer.MAIN requires android SDK

It looks like ThreadEnforcer.Main uses android.os.Looper:

/** A {@link ThreadEnforcer} that confines {@link Bus} methods to the main thread. */
ThreadEnforcer MAIN = new ThreadEnforcer() {
  @Override public void enforce(Bus bus) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
      throw new IllegalStateException("Event bus " + bus + " accessed from non-main thread " + Looper.myLooper());
    }
  }
};

This makes using ThreadEnforcer.MAIN require the android SDK. Thus, a more platform-agnostic version should be used or the documentation should be updated to specify that this is Android-only.

Producer already registered with java 1.8, works fine in 1.7

I'm getting the following error when I build the release of my app with java 1.8, while with java 1.7 there's no issues at all (never seen this error before until I upgraded to java 1.8).

Both Module classes produce their own StatusEvent class, which both inherit from the same abstract BaseStatusEvent class, somehow it seems otto is using the base class to check this in java 1.8.

Below are the relevant pieces of the classes, both modules are created in a single Activity.

FYI; I'm not a java-guru, I just know how to get things done for an android app, so excuse me if there's something really obvious that explains this.
For now I've just switched back to using java1.7, but it would be nice if this wouldn't happen with java1.8.

java.lang.IllegalArgumentException: Producer method for type class nl.tmg.koi.BaseStatusEvent found on type class nl.tmg.upcoming.modules.TopperArticleListModule, but already registered by type class nl.tmg.upcoming.modules.ArticleListModule.
abstract public class BaseStatusEvent {

    private boolean status;
    public BaseStatusEvent(boolean status) {
        this.status = status;
    }

    public boolean isReady() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}
public class TopperArticleListModule {
    @Produce
    public TopperArticleListReady produceListDataStatus() {
        return new TopperArticleListReady();
    }
}

public class TopperArticleListReady extends BaseStatusEvent {
    public TopperArticleListReady(boolean status) {
        super(status);
    }
}
public class ArticleListModule {
    @Produce
    public ArticleListReady produceListDataStatus() {
        return new ArticleListReady();
    }
}

public class ArticleListReady extends BaseStatusEvent {
    public ArticleListReady(boolean status) {
        super(status);
    }
}

PS. using otto-1.3.3 but I don't see any signification changes from 1.3.3 to 1.3.4 that it should differ

inherited providers for qualified dependencies not found by compiler when checking for completeness

If a base module class has a provider method for a qualified dependency, the derived module class is flagged with a compiler error if it has an entry point that depends on the qualified dependency. This gist shows the problem: https://gist.github.com/adennie/5199473.

The workaround is to override the qualified provider in the derived class and delegate to the base class' provider.

This problem doesn't arise if the provider and the dependency don't use qualifiers.

Registering an parent class does not work

I have a parent activity that contains a @Subscribe method. When I try to register the parent using bus.register(this), the AnnotatedHandlerFinder finds all @Subscribe methods in the child class, not in the parent.

That's because:
AnnotatedHandlerFinder.findAllSubscribers() take the class of the instance and not the parent.

A solution would be to add a new method bus.register(this, listenerClass), where listenerClassis the type of the parent object?

How to unregister in plain Java Objects?

In the samples I register and unregister on Bus in the onResume() and onPause() callbacks. But how do I use Otto in plain Java Objects? (no Activity, Fragment and so on). In plain Java Objects I can register in the constructor but where I have to unregister?

Dispatch events asynchronously

There doesn't seem to be a way to configure the event bus so that events are dispatched asynchronously. The Guava EventBus has this functionality in the AsyncBus. I need this functionality so that I can post events from various threads in the app and have them all dispatched on the main looper.

The visibility of EventHandler and EventWithHandler prevent me from simply creating a suitable subclass in my project. I can create a pull request for this functionality, but I wanted to ask first what has a better chance of being integrated?

  1. Simply change the visibility of the two classes above so developers can override all of the protected methods in Bus.
  2. Create an AsyncBus class in the com.squareup.otto package analogous to the version from Guava. Leave the visibility of EventHandler and EventWithHandler as they are.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.