Code Monkey home page Code Monkey logo

rxbus2's Introduction

RxBus2 Release Android Arsenal

RxBus2 - Reactive Event Bus

This is an reactive implementation of an event bus, with a few convenient functions especially useful for handling events with activities, fragments and similar.

RxJava V1: If you are looking for a version for RxJava V1, check out my RXBus

What does it do?

  • it allows you to send events to a bus
  • it allows you to subscribe to special events wherever you want
  • it allows you to queue events until an activity is resumed (to make sure views are accessable for example) and even to pause and resume events => for example, queue events while an activity is paused and emit them as soon as it get's resumed
  • it's very lightweight

Gradle (via JitPack.io)

  1. add jitpack to your project's build.gradle:
repositories {
    maven { url "https://jitpack.io" }
}
  1. add the compile statement to your module's build.gradle:
dependencies {
	implementation 'com.github.MFlisar.RxBus2:lib:<LATEST-VERSION>'
	// optinonal:
	// implementation 'com.github.MFlisar.RxBus2:lib-extension:<LATEST-VERSION>'
	// alternatively, to include ALL modules at once
    // implementation 'com.github.MFlisar:RxBus2:<LATEST-VERSION>'
}

Usage

Content

Demo

Just check out the DemoActivity, it will show the base usage and the difference between the default and the queued RxBus

Simple usage

Use the RxBusBuilder to create Subscriptions or simple Flowables. Just like following:

// Variant 1 - create a simple Flowable:
Flowable<TestEvent> simpleFlowable = RxBusBuilder.create(TestEvent.class).build();

// Variant 2 - subscribe with the BUILDER:
Disposable simpleDisposable = RxBusBuilder.create(TestEvent.class)
    .subscribe(new Consumer<TestEvent>() {
        @Override
        public void accept(TestEvent event) {
            // Event received, handle it...
           }
    });
Sending an event
// Send an event to the bus - all observers that observe this class WITHOUT a key will receive this event
RxBus.get().send(new TestEvent());
// Send an event to the bus - only observers that observe the class AND key will receive this event
RxBus.get()
    .withKey(R.id.observer_key_1)
    .send(new TestEvent());
// Send an event to the bus - all observers that either observe the class or the class AND key will receive this event
RxBus.get()
    .withKey(R.id.observer_key_1)
    .withSendToDefaultBus()
    .send(new TestEvent());
// Send an event to the bus and cast it to a specific class (a base class of multiple classes)
// This allows you to send casted objects to the bus
// so that all observers of the casted class will receive this event 
// (of course only if the cast of the send event is possible, otherwise an exception is thrown!)
RxBus.get()
    .withCast(TestEvent.class)
    .send(new SubTestEvent());

Of course you combine those functionalities as you want!

Advanced usage - QUEUING AND BINDING

You can use this library to subscribe to events and only get them when your activity is resumed, so that you can be sure views are available. Or you can just pause and resume the bus based on any logic you want. Just like following:

RxBusBuilder.create(TestEvent.class)
    // this enables the queuing mode! Passed object must implement IRxBusQueue interface, see the demo app for an example
    .withQueuing(rxBusQueue)
    .withOnNext(new Consumer<TestEvent>() {
        @Override
        public void accept(TestEvent s) {
            // activity IS resumed, you can safely update your UI for example
        }
    })
    .buildSubscription();

Additionally, you can bind the subscription to an object and afterwards call RxDisposableManager.unsubscribe(boundObject); to unsubcribe ANY subscription that was bound to boundObject just like following:

// boundObject... can be for example your activity
RxBusBuilder.create(TestEvent.class)
    // this enables the queuing mode! Passed object must implement IRXBusQueue interface, see the demo app for an example
    .withQueuing(rxBusQueue)
    .withBound(boundObject)
    .subscribe(new Consumer<TestEvent>() {
        @Override
        public void accept(TestEvent s) {
            // activity IS resumed, you can safely update your UI for example
         }
    });
// call this for example in your activities onDestroy or wherever appropriate to unsubscribe ALL subscriptions at once that are bound to the boundOBject
RxDisposableManager.unsubscribe(boundObject);
Advanced usage - KEYS

You can use this library to subscribe to events of a typ and ONLY get them when it was send to the bus with a special key (and and additionally only when your activity is resumed, as this example shows via .withQueuing()), so that you can distinct event subscriptions of the same class based on a key (the key can be an Integer or a String). Just like following:

RxBusBuilder.create(TestEvent.class)
    // this enables the binding to the key
    .withKey(R.id.observer_key_1) // you can provide multiple keys as well
    .withQueuing(rxBusQueue)
    .withBound(boundObject)
    .subscribe(new Consumer<TestEvent>() {
        @Override
        public void accept(TestEvent event) {
            // activity IS resumed, you can safely update your UI for example
        }
    });
Advanced usage - Transfrom

You can pass in a FlowableTransformer to transform the observed event to whatever you want!

FlowableTransformer<TestEvent, TestEventTransformed> transformer = new FlowableTransformer<TestEvent, TestEventTransformed>() {
    @Override
    public Observable<TestEventTransformed> apply(Flowable<TestEvent> observable) {
        return observable
                .map(new Function<TestEvent, TestEventTransformed>() {
                    @Override
                    public TestEventTransformed apply(TestEvent event) {
                        return event.transform();
                    }
                });
    }
};
RxBusBuilder.create(TestEvent.class)
    .withQueuing(rxBusQueue)
    .withBound(boundObject)
    .subscribe(new Consumer<TestEventTransformed>() {
        @Override
        public void accept(TestEventTransformed transformedEvent) {
        }
    }, transformer);
Advanced usage - Sub Classes

By default, sub class handling is disabled and you must use RxBus.withCast(BaseClass.class) to send sub classes to base class observers (and only to the base class observers). You have two other options for handling this.

  • Use RxBus.get().withSendToSuperClasses(true).send(subClassEvent) - this will send the event to all super class observers of the send event as well
  • Enable above by default via RxBusDefaults.get().setSendToSuperClassesAsWell(true) then all events that are send via RxBus.get().sendEvent(subClassEvent) are send to all super classes of the send event as well

If you enable RxBusDefaults.get().setSendToSuperClassesAsWell(true), you can still overwrite this global default value for a single event by sending the event via RxBus.get().withSendToSuperClasses(false).send(subClassEvent) o a per event base.

Helper class - RxDisposableManager

This class helps to bind Disposables to objects and offers an easy way to unsubscribe all Disposables that are bound to an object at once. You can simply use this directly via RxDisposableManager.addDisposable(boundObject, flowable) or use it directly with the RxBusBuilder via the RxBusBuilder.withBound(boundObject) which will automatically add the Disposable to the RxDisposableManager as soon as you call RxBusBuilder.subscribe(...). This will automatically add the Disposable to the RxDisposableManager when you call RxBusBuilder.subscribe(...). Afterwards you unsubscribe via RxDisposableManager.unsubscribe(boundObject);. The bound object can be an Activity or Fragment for example, but any other object as well.

Example - Direct usage

Subscription subscription = RxBusBuilder.create(...).subscribe(...);
RxDisposableManager.addDisposable(activity, subscription);

Example - RxBusBuilder

RxBusBuilder.create(...).withBound(activity)...;

Now you only have to make sure to unsubscribe again like following:

RxDisposableManager.unsubscribe(activity);

This will remove ANY subscription that is bound to activity and therefore this can be used in your activity's onDestroy method to make sure ALL subscriptions are unsubscribed at once so that you don't leak the activity.

rxbus2's People

Contributors

mflisar 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

rxbus2's Issues

如何调用.bindToLifecycle

RxBusBuilder.create(CityEvent::class.java).build().bindToLifecycle(mActivity.findViewById(android.R.id.content)).subscribe {
}
现在这么写bindToLifecycle报错,不知道如何解决。求指教

Casting - one time problem with queueing

Following happens:

Case 1 - Correct

  • unlock your screen and start the demo

Following TestEvent logs will be printed:

DemoActivity: Type: QUEUED BUS [ActualClass: TestEvent] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
// following 4 events are lost in the second test scenario
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent1] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent2] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent3] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent4] (key=NONE), Event: TEST - SUBCLASS4 and QUEUED - TestSubEvent4
DemoActivity: Type: SIMPLE BUS [ActualClass: TestEvent] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent1] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent2] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent3] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestEvent - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent1 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent2 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent3 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestEvent - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent1 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent2 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent3 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent4 - from thread] (key=NONE), Event: TEST - SUBCLASS4 and QUEUED - TestSubEvent4

Case 2 - Incorrect

  • lock your screen and start the app with the android studio start button
  • wait 5 seconds, so that the TestEvents from the background are emitted as well
  • unlock the screen to resume the demo app

Following is printed:

DemoActivity: Type: SIMPLE BUS [ActualClass: TestEvent] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent1] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent2] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent3] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestEvent] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestEvent - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent1 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent2 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: SIMPLE BUS [ActualClass: TestSubEvent3 - from thread] (key=NONE), Event: TEST - BASE CLASS and not queued - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestEvent] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestEvent - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent1 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent2 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent3 - from thread] (key=NONE), Event: TEST - BASE CLASS and QUEUED - TestEvent
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent4] (key=NONE), Event: TEST - SUBCLASS4 and QUEUED - TestSubEvent4
DemoActivity: Type: QUEUED BUS [ActualClass: TestSubEvent4 - from thread] (key=NONE), Event: TEST - SUBCLASS4 and QUEUED - TestSubEvent4

Problem

Prerequisitions

  • emit casted sub events
  • emit it before activity is resumed
  • queuing must be enabled

All casted events that were emitted BEFORE the activity was resumed for the first the time AND are casted got lost (in the example those are the 4 sub class events that are emitted in the activity on start). This ONLY happens if queuing is enabled. If they are not casted they are not lost, weird, because casting means, that the casted events are emitted, so for the bus, it should not make any difference if a sub class of TestEvent in a casted way or a TestEvent is send to the bus...

I currently don't see any reason why this is happening...

Improved setup possibilities for handling sub classes

If you have following:

  • BaseClass
  • A extends BaseClass
  • B extends BaseClass

you currently have to take care to send A and B as casted events if you want any BaseClass observers to get the events (and then only those BaseClass observers get the event, not the concrete sub class observers). It would be better to tell the bus that you want to listen to BaseClass and any inherited class instead. This setup is more flexible and more error prone.

Currently I have no fast idea how to achieve that...

Maybe someone has a good idea?

Annotation processor

Idea

  1. Define subcriptions via annotations:

     @RxBusSubscribe
     public void onEvent(Event event) {
         // handle bus event here
     }
    
  2. Annotation processor should generate functions in this class:

     public final void subscribeRxBusEvents() {
          // generated code
          // disposables must be managed by the class so those are bound to this class
     }
    
    public final void unsubscribeRxBusEvents() {
        RxDisposableManager.unsubscribe(this);
    }
    
  3. user calls subscribeRxBusEvents() wherever he wants to subscribe all annotated functions in this class to bus - manually

  4. user also calls unsubscribeRxBusEvents() wherever he wants to unsubscribe all annotated functions in this class from bus - manually

Settings

@RxBusSubscribe has following annotation fields:

  • queuing... defines the RxBusBuilders withQueuing value
  • mode... defines the RxBusBuilders withMode value
  • key/keys... defines the RxBusBuilders withKey value

RxBusBuilder.create(<CLASS>.class) is derived from the annotated functions parameter class. public void onEvent(Event event) will generate a RxBusBuilder.create(Event.class) code line

Examples

    @RxBusSubscribe(queuing = false, mode = RxBusMode.Main)
    public void onEvent(Event event) {
        // handle bus event here
    }        

    @RxBusSubscribe(queuing = false, mode = RxBusMode.Main, key = R.integer.key1)
    public void onEvent(Event event) {
        // handle bus event here
    }

    @RxBusSubscribe(queuing = true, mode = RxBusMode.Background, keys = {R.integer.key1, R.integer.key2})
    public void onEvent(Event event) {
        // handle bus event here
    }

    @RxBusSubscribe(queuing = true, mode = RxBusMode.Background, keys = {"key1", "key2"})
    public void onEvent(Event event) {
        // handle bus event here
    }

TODO

  • just a idea so far
  • rethink annotation names
  • maybe enable auto subscribtion/unsubscription for classes with lifecycle via an additional annotation for the class itself (for Activity/Fragment/...). This could generate code that subscribes to the bus in the constructor/onCreate/onResume and unsubscribes them in the appropriate counter function

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.