├── rxbus
├── .gitignore
├── gradle.properties
├── build.gradle
└── src
│ ├── test
│ └── java
│ │ └── net
│ │ └── jokubasdargis
│ │ └── rxbus
│ │ ├── Event.java
│ │ ├── QueueTest.java
│ │ └── RxBusTest.java
│ └── main
│ └── java
│ └── net
│ └── jokubasdargis
│ └── rxbus
│ ├── Bus.java
│ ├── DefaultEventRelay.java
│ ├── ReplayEventRelay.java
│ ├── Queue.java
│ └── RxBus.java
├── rxbus-android
├── .gitignore
├── gradle.properties
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── net
│ │ │ └── jokubasdargis
│ │ │ └── rxbus
│ │ │ └── AndroidRxBus.java
│ └── test
│ │ └── java
│ │ └── net
│ │ └── jokubasdargis
│ │ └── rxbus
│ │ ├── Event.java
│ │ └── AndroidRxBusTest.java
└── build.gradle
├── rxbus-dispatcher
├── .gitignore
├── gradle.properties
├── build.gradle
└── src
│ ├── test
│ └── java
│ │ └── net
│ │ └── jokubasdargis
│ │ └── rxbus
│ │ ├── EventA.java
│ │ ├── RxBusDispatcherTest.java
│ │ ├── DefaultFlusherTest.java
│ │ └── DefaultDispatcherTest.java
│ └── main
│ └── java
│ └── net
│ └── jokubasdargis
│ └── rxbus
│ ├── Flushable.java
│ ├── Flusher.java
│ ├── Station.java
│ ├── Dispatcher.java
│ ├── ErrorListener.java
│ ├── DefaultFlusher.java
│ ├── DefaultDispatcher.java
│ └── RxBusDispatcher.java
├── assets
├── eventbus_1.jpg
└── eventbus_2.jpg
├── settings.gradle
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── checkstyle.gradle
├── android-findbugs.gradle
└── mvn-push.gradle
├── gradle.properties
├── .buildscript
└── deploy_snapshot.sh
├── .gitignore
├── .travis.yml
├── README.md
├── gradlew.bat
├── checkstyle.xml
├── gradlew
└── LICENSE.txt
/rxbus/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/rxbus-android/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/rxbus/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=rxbus
2 | POM_NAME=RxBus
3 | POM_PACKAGING=jar
4 |
--------------------------------------------------------------------------------
/assets/eventbus_1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleventigers/rxbus/HEAD/assets/eventbus_1.jpg
--------------------------------------------------------------------------------
/assets/eventbus_2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleventigers/rxbus/HEAD/assets/eventbus_2.jpg
--------------------------------------------------------------------------------
/rxbus-android/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=rxbus-android
2 | POM_NAME=RxBus Android
3 | POM_PACKAGING=aar
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'rxbus-root'
2 |
3 | include ':rxbus', ':rxbus-android', 'rxbus-dispatcher'
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleventigers/rxbus/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/rxbus-dispatcher/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=rxbus-dispatcher
2 | POM_NAME=RxBusDispatcher
3 | POM_PACKAGING=jar
4 |
--------------------------------------------------------------------------------
/rxbus-android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jun 25 17:20:11 BST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.9-all.zip
7 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply from: rootProject.file('gradle/checkstyle.gradle')
3 |
4 | dependencies {
5 | compile project(':rxbus')
6 | testCompile rootProject.ext.junit
7 | testCompile rootProject.ext.mockito
8 | testCompile rootProject.ext.truth
9 | }
10 |
11 | sourceCompatibility = rootProject.ext.javaVersion
12 | targetCompatibility = rootProject.ext.javaVersion
13 |
14 | apply from: rootProject.file('gradle/mvn-push.gradle')
--------------------------------------------------------------------------------
/rxbus/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply from: rootProject.file('gradle/checkstyle.gradle')
3 |
4 | dependencies {
5 | compile rootProject.ext.rxJava
6 | compile rootProject.ext.rxRelay
7 | testCompile rootProject.ext.junit
8 | testCompile rootProject.ext.mockito
9 | }
10 |
11 | sourceCompatibility = rootProject.ext.javaVersion
12 | targetCompatibility = rootProject.ext.javaVersion
13 |
14 | apply from: rootProject.file('gradle/mvn-push.gradle')
15 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | GROUP=net.jokubasdargis.rxbus
2 |
3 | VERSION_NAME=2.0.1-SNAPSHOT
4 |
5 | POM_DESCRIPTION=Event bus running on type safe RxJava queues
6 | POM_URL=https://github.com/eleventigers/rxbus
7 | POM_SCM_URL=https://github.com/eleventigers/rxbus
8 | POM_SCM_CONNECTION=scm:git:git://github.com/eleventigers/rxbus.git
9 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com:eleventigers/rxbus.git
10 |
11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
13 | POM_LICENCE_DIST=repo
14 |
15 | POM_DEVELOPER_ID=eleventigers
16 | POM_DEVELOPER_NAME=Jokubas Dargis
--------------------------------------------------------------------------------
/gradle/checkstyle.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'checkstyle'
2 |
3 | checkstyle {
4 | configFile rootProject.file('checkstyle.xml')
5 | showViolations true
6 | }
7 |
8 | if (plugins.hasPlugin('com.android.library')) {
9 | android.libraryVariants.all { variant ->
10 | def name = variant.buildType.name
11 | def checkstyle = project.tasks.create "checkstyle${name.capitalize()}", Checkstyle
12 | checkstyle.dependsOn variant.javaCompile
13 | checkstyle.source variant.javaCompile.source
14 | checkstyle.classpath = project.fileTree(variant.javaCompile.destinationDir)
15 | checkstyle.exclude('**/BuildConfig.java')
16 | checkstyle.exclude('**/R.java')
17 | project.tasks.getByName("check").dependsOn checkstyle
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/test/java/net/jokubasdargis/rxbus/EventA.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | class EventA { }
20 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/Flushable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | @SuppressWarnings("WeakerAccess")
20 | public interface Flushable {
21 |
22 | void flush();
23 | }
24 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/Flusher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | @SuppressWarnings("WeakerAccess")
20 | public interface Flusher {
21 |
22 | void schedule(Flushable flushable);
23 | }
24 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/Station.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | @SuppressWarnings("WeakerAccess")
20 | public interface Station extends Flushable {
21 |
22 | void receive(T event);
23 | }
24 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/Dispatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | @SuppressWarnings("WeakerAccess")
20 | public interface Dispatcher {
21 |
22 | void publish(Queue queue, T event);
23 |
24 | void register(Queue queue, Station station);
25 |
26 | void unregister(Station station);
27 | }
28 |
--------------------------------------------------------------------------------
/.buildscript/deploy_snapshot.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo.
4 | #
5 | # Adapted from https://coderwall.com/p/9b_lfq and
6 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/
7 |
8 | SLUG="eleventigers/rxbus"
9 | JDK="oraclejdk8"
10 | BRANCH="develop"
11 |
12 | set -e
13 |
14 | if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then
15 | echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'."
16 | elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then
17 | echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'."
18 | elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
19 | echo "Skipping snapshot deployment: was pull request."
20 | elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then
21 | echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'."
22 | else
23 | echo "Deploying snapshot..."
24 | ./gradlew clean uploadArchives
25 | echo "Snapshot deployed!"
26 | fi
27 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/ErrorListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | @SuppressWarnings("WeakerAccess")
20 | public interface ErrorListener {
21 |
22 | void onError(Throwable throwable);
23 |
24 | ErrorListener NOOP = new ErrorListener() {
25 | @Override
26 | public void onError(Throwable throwable) {
27 | // no-op
28 | }
29 | };
30 | }
31 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/test/java/net/jokubasdargis/rxbus/RxBusDispatcherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import static com.google.common.truth.Truth.assertThat;
20 |
21 | import org.junit.Test;
22 |
23 | public class RxBusDispatcherTest {
24 |
25 | @Test
26 | public void builderDefault() {
27 | Dispatcher dispatcher = RxBusDispatcher.builder().build();
28 |
29 | assertThat(dispatcher).isNotNull();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/gradle/android-findbugs.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'findbugs'
2 |
3 | afterEvaluate {
4 | def variants = plugins.hasPlugin('com.android.application') ?
5 | android.applicationVariants : android.libraryVariants
6 |
7 | variants.each { variant ->
8 | def task = tasks.create("findBugs${variant.name.capitalize()}", FindBugs)
9 |
10 | task.group = 'verification'
11 | task.description = "Run FindBugs for the ${variant.description}."
12 |
13 | task.effort = 'max'
14 |
15 | task.reportLevel = 'high'
16 | task.reports {
17 | xml {
18 | enabled = false
19 | }
20 | html {
21 | enabled = true
22 | }
23 | }
24 |
25 | def variantCompile = variant.javaCompile
26 |
27 | task.classes = fileTree(variantCompile.destinationDir)
28 | task.source = variantCompile.source
29 | task.classpath = variantCompile.classpath.plus(project.files(android.bootClasspath))
30 |
31 | task.dependsOn(variantCompile)
32 | tasks.getByName('check').dependsOn(task)
33 | }
34 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ###Android###
2 |
3 | # Built application files
4 | *.apk
5 | *.ap_
6 |
7 | # Files for the Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 |
17 | # Gradle files
18 | .gradle/
19 | build/
20 |
21 | # Local configuration file (sdk path, etc)
22 | local.properties
23 |
24 | # Proguard folder generated by Eclipse
25 | proguard/
26 |
27 | # Log Files
28 | *.log
29 |
30 |
31 | ###OSX###
32 |
33 | .DS_Store
34 | .AppleDouble
35 | .LSOverride
36 |
37 | # Icon must end with two \r
38 | Icon
39 |
40 |
41 | # Thumbnails
42 | ._*
43 |
44 | # Files that might appear on external disk
45 | .Spotlight-V100
46 | .Trashes
47 |
48 | # Directories potentially created on remote AFP share
49 | .AppleDB
50 | .AppleDesktop
51 | Network Trash Folder
52 | Temporary Items
53 | .apdisk
54 |
55 |
56 | ###Linux###
57 |
58 | *~
59 |
60 | # KDE directory preferences
61 | .directory
62 |
63 |
64 | ###Windows###
65 |
66 | # Windows image file caches
67 | Thumbs.db
68 | ehthumbs.db
69 |
70 | # Folder config file
71 | Desktop.ini
72 |
73 | # Recycle Bin used on file shares
74 | $RECYCLE.BIN/
75 |
76 | # Windows Installer files
77 | *.cab
78 | *.msi
79 | *.msm
80 | *.msp
81 |
82 | # Windows shortcuts
83 | *.lnk
84 |
85 |
86 | ###IntelliJ###
87 |
88 | *.iml
89 | *.ipr
90 | *.iws
91 | .idea/
92 |
93 |
94 | ###Gradle###
95 |
96 | .gradle
97 | build/
--------------------------------------------------------------------------------
/rxbus/src/test/java/net/jokubasdargis/rxbus/Event.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.concurrent.TimeUnit;
20 |
21 | final class Event {
22 |
23 | static Event create() {
24 | return new Event(System.nanoTime());
25 | }
26 |
27 | static Event create(long timestamp) {
28 | return new Event(timestamp);
29 | }
30 |
31 | private final long timestampNanos;
32 |
33 | private Event(long timestamp) {
34 | this.timestampNanos = timestamp;
35 | }
36 |
37 | public long getTimestamp(TimeUnit unit) {
38 | return unit.convert(timestampNanos, TimeUnit.NANOSECONDS);
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | return "Event{"
44 | + "timestamp=" + timestampNanos
45 | + '}';
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/rxbus-android/src/test/java/net/jokubasdargis/rxbus/Event.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.concurrent.TimeUnit;
20 |
21 | final class Event {
22 |
23 | static Event create() {
24 | return new Event(System.nanoTime());
25 | }
26 |
27 | static Event create(long timestamp) {
28 | return new Event(timestamp);
29 | }
30 |
31 | private final long timestampNanos;
32 |
33 | private Event(long timestamp) {
34 | this.timestampNanos = timestamp;
35 | }
36 |
37 | public long getTimestamp(TimeUnit unit) {
38 | return unit.convert(timestampNanos, TimeUnit.NANOSECONDS);
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | return "Event{"
44 | + "timestamp=" + timestampNanos
45 | + '}';
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/rxbus-android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | dependencies {
3 | classpath rootProject.ext.androidPlugin
4 | }
5 | }
6 |
7 | apply plugin: 'com.android.library'
8 | apply from: rootProject.file('gradle/android-findbugs.gradle')
9 | apply from: rootProject.file('gradle/checkstyle.gradle')
10 |
11 | dependencies {
12 | compile project(':rxbus')
13 | compile rootProject.ext.rxAndroid
14 | compile rootProject.ext.supportAnnotations
15 | testCompile rootProject.ext.junit
16 | testCompile rootProject.ext.mockito
17 | }
18 |
19 | android {
20 | compileSdkVersion rootProject.ext.compileSdkVersion
21 | buildToolsVersion rootProject.ext.buildToolsVersion
22 |
23 | defaultConfig {
24 | minSdkVersion rootProject.ext.minSdkVersion
25 |
26 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
27 | }
28 |
29 | compileOptions {
30 | sourceCompatibility rootProject.ext.javaVersion
31 | targetCompatibility rootProject.ext.javaVersion
32 | }
33 |
34 | dexOptions {
35 | preDexLibraries = !rootProject.ext.ci
36 | }
37 |
38 | lintOptions {
39 | textReport true
40 | textOutput 'stdout'
41 | disable 'InvalidPackage'
42 | }
43 |
44 | packagingOptions {
45 | exclude 'LICENSE.txt'
46 | }
47 |
48 | buildTypes {
49 | debug {
50 | testCoverageEnabled true
51 | }
52 | }
53 | }
54 |
55 | apply from: rootProject.file('gradle/mvn-push.gradle')
56 |
--------------------------------------------------------------------------------
/rxbus/src/test/java/net/jokubasdargis/rxbus/QueueTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import static org.junit.Assert.assertEquals;
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import org.junit.Test;
23 |
24 | public final class QueueTest {
25 |
26 | @Test
27 | public void buildQueueOfEventType() {
28 | Queue queue = Queue.of(Event.class).build();
29 | assertTrue(Event.class.equals(queue.getEventType()));
30 | }
31 |
32 | @Test
33 | public void buildQueueWithName() {
34 | Queue queue = Queue.of(Event.class)
35 | .name("TestQueue")
36 | .build();
37 | assertEquals("TestQueue", queue.getName());
38 | }
39 |
40 | @Test
41 | public void incrementingQueueId() {
42 | Queue queue1 = Queue.of(Event.class).build();
43 | Queue queue2 = Queue.of(Event.class).build();
44 | assertTrue(queue1.getId() < queue2.getId());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/rxbus/src/main/java/net/jokubasdargis/rxbus/Bus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.Relay;
20 |
21 | import rx.Observer;
22 | import rx.Scheduler;
23 | import rx.Subscription;
24 |
25 | /**
26 | * Event notification system which enforces use of dedicated queues to perform type safe pub/sub.
27 | */
28 | @SuppressWarnings("WeakerAccess")
29 | public interface Bus {
30 |
31 | /**
32 | * Subscribes observer to observe events from the given queue.
33 | */
34 | Subscription subscribe(Queue queue, Observer observer);
35 |
36 | /**
37 | * Subscribes observer to observe events from the given queue on the given scheduler.
38 | */
39 | Subscription subscribe(Queue queue, Observer observer, Scheduler scheduler);
40 |
41 | /**
42 | * Publishes event onto the given queue.
43 | */
44 | void publish(Queue queue, T event);
45 |
46 | /**
47 | * Converts the given {@link Queue} to a {@link Relay} to be used
48 | * outside the bus context (when combining Rx streams).
49 | */
50 | Relay queue(Queue queue);
51 | }
52 |
--------------------------------------------------------------------------------
/rxbus/src/main/java/net/jokubasdargis/rxbus/DefaultEventRelay.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.PublishRelay;
20 | import com.jakewharton.rxrelay.Relay;
21 |
22 | import rx.Subscriber;
23 |
24 | final class DefaultEventRelay extends Relay {
25 |
26 | public static DefaultEventRelay create() {
27 | return new DefaultEventRelay<>(new OnSubscribeFunc());
28 | }
29 |
30 | private final Relay wrappedRelay;
31 |
32 | private DefaultEventRelay(OnSubscribeFunc onSubscribeFunc) {
33 | super(onSubscribeFunc);
34 | wrappedRelay = onSubscribeFunc.relay;
35 | }
36 |
37 | @Override
38 | public void call(T event) {
39 | wrappedRelay.call(event);
40 | }
41 |
42 | @Override
43 | public boolean hasObservers() {
44 | return wrappedRelay.hasObservers();
45 | }
46 |
47 | private static final class OnSubscribeFunc implements OnSubscribe {
48 |
49 | private final PublishRelay relay = PublishRelay.create();
50 |
51 | public void call(Subscriber super T> subscriber) {
52 | relay.subscribe(subscriber);
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | android:
3 | components:
4 | - build-tools-23.0.1
5 | - android-23
6 | - extra-android-m2repository
7 | jdk:
8 | - oraclejdk8
9 | script:
10 | - ./gradlew ":$MODULE:build"
11 | after_success:
12 | - ".buildscript/deploy_snapshot.sh"
13 | env:
14 | matrix:
15 | - MODULE=rxbus
16 | - MODULE=rxbus-android
17 | - MODULE=rxbus-dispatcher
18 | global:
19 | - secure: sBk32v3IvSnVRmTG3MfbF1GAW/Zd8FZtqIvBsYCOQyG8R1a6nlcXPdVJpFNeqGnSAREt3pEVAZLR3DqQSE5Mt4h5X075xn7I4786/GkeE6MKpEpxHfHMZxJ45wmqET3G0uB616EwhR2Ps7WtyoscH+90d6r9B71SgEip0p2Fic/wfU9uSvgawZKyaGdKDK91Pk/SOj72JlWpkUfc4ltfWKVAAuWTYmSxZm0UNcMssshFv6aiaskDeBC+qb4T1LlO5YJtA3fwlgqjy+8MYfbexuuE1BfyFVo7v3Epbk6pqeOj3v46m0JfFvKVoAjEYqE/7BLUUJbsVBjnJqTCb4ltZC78wBFXmiccuSrjmSXvOCTjesatOf0WT/zixsw3ijcf5dm/lbJI0W8jhrY3hWkPquZd8OCg6aIxLIg7CEGkuu7ZYmEQRQ6gs+klA8XK5GKm18oAris9VhiQax+sfpCupohL+JWID+c9lNGsue1kDnHZSqHhUsFZjuSLDkd2vbOvtOsz9IUnK1x+ilT7ICBBJ4zbBxQrmra4u7M3cUF10QW+7KUaR1rwaIEeVHkV1x83eth7fCeR+EV7hOpA5wJ8er7Ej/DxpMfsJM+OCIBgWCogDyu1OPBBXYgecHRGG0fWcErl3bGY5PuwvtlmKJ4mmzrxdU3cgLXGSams3VQIQo4=
20 | - secure: d8VDTMqfLzKbxFs3l96AHbL2PV8h49+hHcaOc5bk1weTH5elqiou5+hFHOHr+sByLzv95VZ9NqFCWph6GwxZYxIWfHdlQO/CLEM9p9/IX50pjer0Mww+D25bJXTDUyJrHVodxXkWhLruLJgkTD1uAT4ouQl+4RnT/rLPJTs9dDFz5csL58dUx/+9ZJB3AvJ/6LITUdxtutb15jPeG+3u7JoDymks0gcgmgQdfxEQv9e0r3vpT6Xm86FJ7rat84t1lXKnb3Pw7R8s2YvE48MB9EENr2wkBsuDk/WdszMJGra/MkzNtpbQRGr4qYihwnf3qzMdBlOs9L93XM/K9rLn9uQErOBP9le4KODAIM44KwA42VmSbuPHPnNWfYW+XOdYpDP76JnvecNc4Vyz+9H+CEfpHN47DqhWNwdNzmf2udVBW6znkFSW9CsVpbz7Mjj9zEcoHA9e/fcx4HsPXflt2nvXWnHDr0FSqLzKyUEgXO/rF0e5USrdjyHUU7RcsRT7uEwrL0jIEx0jiXdyZ7Jlsqs+XhW5yi/E5ECHLHFn+xkdOlXI0AADGFOJ3j1/5xBo0xgyvpTzoxspBRDc1xRPHa7ME4YyZclOZ2UTHHeEIQrubPASEEFBP1zhRtnp6Vpqn0wNkGq661EELEo4nYsnw5Jnisbur/Xo4cO7p82ibkk=
21 | branches:
22 | except:
23 | - gh-pages
24 | notifications:
25 | email: false
26 | sudo: false
27 | cache:
28 | directories:
29 | - "$HOME/.gradle"
30 |
--------------------------------------------------------------------------------
/rxbus/src/main/java/net/jokubasdargis/rxbus/ReplayEventRelay.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.BehaviorRelay;
20 | import com.jakewharton.rxrelay.Relay;
21 |
22 | import rx.Subscriber;
23 |
24 | final class ReplayEventRelay extends Relay {
25 |
26 | public static ReplayEventRelay create() {
27 | return new ReplayEventRelay<>(new OnSubscribeFunc(null));
28 | }
29 |
30 | public static ReplayEventRelay create(T event) {
31 | return new ReplayEventRelay<>(new OnSubscribeFunc<>(event));
32 | }
33 |
34 | private final Relay wrappedRelay;
35 |
36 | private ReplayEventRelay(OnSubscribeFunc onSubscribeFunc) {
37 | super(onSubscribeFunc);
38 | wrappedRelay = onSubscribeFunc.relay;
39 | }
40 |
41 | @Override
42 | public void call(T event) {
43 | wrappedRelay.call(event);
44 | }
45 |
46 | @Override
47 | public boolean hasObservers() {
48 | return wrappedRelay.hasObservers();
49 | }
50 |
51 | private static final class OnSubscribeFunc implements OnSubscribe {
52 |
53 | private final BehaviorRelay relay;
54 |
55 | private OnSubscribeFunc(T event) {
56 | if (event == null) {
57 | relay = BehaviorRelay.create();
58 | } else {
59 | relay = BehaviorRelay.create(event);
60 | }
61 | }
62 |
63 | @Override
64 | public void call(Subscriber super T> subscriber) {
65 | relay.subscribe(subscriber);
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/test/java/net/jokubasdargis/rxbus/DefaultFlusherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import static org.mockito.Mockito.mock;
20 | import static org.mockito.Mockito.verify;
21 | import static org.mockito.Mockito.verifyNoMoreInteractions;
22 | import static org.mockito.Mockito.verifyZeroInteractions;
23 |
24 | import java.util.concurrent.TimeUnit;
25 | import org.junit.Test;
26 | import rx.schedulers.Schedulers;
27 | import rx.schedulers.TestScheduler;
28 |
29 | public final class DefaultFlusherTest {
30 |
31 | private final Flushable flushable1 = mock(Flushable.class);
32 | private final Flushable flushable2 = mock(Flushable.class);
33 | private final TestScheduler scheduler = Schedulers.test();
34 | private final Flusher flusher = DefaultFlusher.create(scheduler, 1, TimeUnit.SECONDS);
35 |
36 | @Test
37 | public void singleSchedule() {
38 | flusher.schedule(flushable1);
39 | scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
40 | scheduler.triggerActions();
41 |
42 | verify(flushable1).flush();
43 | }
44 |
45 | @Test
46 | public void multipleSchedule() {
47 | flusher.schedule(flushable1);
48 | flusher.schedule(flushable2);
49 |
50 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
51 |
52 | verifyZeroInteractions(flushable1, flushable2);
53 |
54 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS);
55 | scheduler.triggerActions();
56 |
57 | verify(flushable1).flush();
58 | verify(flushable2).flush();
59 |
60 | verifyNoMoreInteractions(flushable1, flushable2);
61 | }
62 |
63 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | RxBus
2 | =====
3 | Event bus running on type safe RxJava queues
4 |
5 | Download
6 | --------
7 | Gradle:
8 | ```groovy
9 | compile 'net.jokubasdargis.rxbus:rxbus:2.0.0'
10 |
11 | // Optional
12 | compile 'net.jokubasdargis.rxbus:rxbus-android:2.0.0'
13 | compile 'net.jokubasdargis.rxbus:rxbus-dispatcher:2.0.0'
14 | ```
15 |
16 | Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap].
17 |
18 | Usage
19 | -----
20 |
21 | **Basic use - event delivery transport tightly coupled by an event type**
22 |
23 | * Create a default bus
24 |
25 | ```java
26 | Bus bus = RxBus.create();
27 | ```
28 |
29 | or if you are on Android:
30 |
31 | ```java
32 | Bus bus = RxAndroidBus.create();
33 | ```
34 |
35 | * Prepare a Queue for an event type. You might want to maintain a collection of static queues as:
36 |
37 | ```java
38 | public final class Queues {
39 | public static final Queue TRACKING = Queue.of(TrackingEvent.class).build();
40 | }
41 | ```
42 |
43 | * Use a queue when subscribing
44 |
45 | ```java
46 | Subscription subscription = bus.subscribe(Queues.TRACKING, new Observer {
47 | ...
48 | @Override
49 | public void onNext(TrackingEvent event) {
50 | // do something with the event
51 | }
52 | })
53 | ```
54 |
55 | * and publishing:
56 |
57 | ```java
58 | bus.publish(Queues.TRACKING, new TrackingEvent())
59 | ```
60 |
61 |
62 | Origin
63 | ------
64 | Adapted from Soundcloud's reactive bus appraoch as seen in [mttkay's](https://github.com/mttkay) [Reactive Soundcloud](https://speakerdeck.com/mttkay/reactive-soundcloud-tackling-complexity-in-large-applications) slides:
65 |
66 | 
67 |
68 | 
69 |
70 | License
71 | -------
72 |
73 | Copyright 2016 Jokubas Dargis
74 |
75 | Licensed under the Apache License, Version 2.0 (the "License");
76 | you may not use this file except in compliance with the License.
77 | You may obtain a copy of the License at
78 |
79 | http://www.apache.org/licenses/LICENSE-2.0
80 |
81 | Unless required by applicable law or agreed to in writing, software
82 | distributed under the License is distributed on an "AS IS" BASIS,
83 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
84 | See the License for the specific language governing permissions and
85 | limitations under the License.
86 |
87 |
88 | [snap]: https://oss.sonatype.org/content/repositories/snapshots/
89 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/DefaultFlusher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.Deque;
20 | import java.util.concurrent.ConcurrentLinkedDeque;
21 | import java.util.concurrent.TimeUnit;
22 | import rx.Scheduler;
23 | import rx.functions.Action0;
24 | import rx.subscriptions.SerialSubscription;
25 | import rx.subscriptions.Subscriptions;
26 |
27 | final class DefaultFlusher implements Flusher {
28 |
29 | private final Scheduler scheduler;
30 | private final long flushDelayNanos;
31 | private final Deque flushables = new ConcurrentLinkedDeque<>();
32 | private final FlushAction flushAction = new FlushAction();
33 | private final SerialSubscription subscription = new SerialSubscription();
34 |
35 | static Flusher create(Scheduler scheduler, long flushDelay, TimeUnit flushDelayUnit) {
36 | return new DefaultFlusher(scheduler, flushDelay, flushDelayUnit);
37 | }
38 |
39 | private DefaultFlusher(Scheduler scheduler, long flushDelay, TimeUnit flushDelayUnit) {
40 | this.scheduler = scheduler;
41 | this.flushDelayNanos = flushDelayUnit.toNanos(flushDelay);
42 | resetSubscription();
43 | }
44 |
45 | @Override
46 | public void schedule(Flushable flushable) {
47 | flushables.add(flushable);
48 | scheduleFlush();
49 | }
50 |
51 | private void scheduleFlush() {
52 | if (subscription.get() == Subscriptions.unsubscribed()) {
53 | subscription.set(scheduler.createWorker().schedule(
54 | flushAction, flushDelayNanos, TimeUnit.NANOSECONDS));
55 | }
56 | }
57 |
58 | private void resetSubscription() {
59 | subscription.set(Subscriptions.unsubscribed());
60 | }
61 |
62 | private class FlushAction implements Action0 {
63 |
64 | @Override
65 | public void call() {
66 | while (!flushables.isEmpty()) {
67 | Flushable flushable = flushables.remove();
68 | flushable.flush();
69 | resetSubscription();
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/rxbus-android/src/main/java/net/jokubasdargis/rxbus/AndroidRxBus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import android.util.Log;
20 | import android.util.SparseArray;
21 |
22 | import com.jakewharton.rxrelay.Relay;
23 |
24 | import rx.Observer;
25 | import rx.Scheduler;
26 | import rx.Subscription;
27 | import rx.android.schedulers.AndroidSchedulers;
28 |
29 | /**
30 | * Simple {@link Bus} implementation with {@link Queue} caching and logging specific
31 | * to the Android platform. By default subscriptions are observed on the main thread.
32 | */
33 | @SuppressWarnings("WeakerAccess")
34 | public final class AndroidRxBus implements Bus {
35 |
36 | public static AndroidRxBus create() {
37 | return create(new AndroidQueueCache());
38 | }
39 |
40 | public static AndroidRxBus create(RxBus.QueueCache cache) {
41 | return create(cache, new RxBus.Logger() {
42 | @Override
43 | public void log(String message) {
44 | Log.d(TAG, message);
45 | }
46 | });
47 | }
48 |
49 | public static AndroidRxBus create(RxBus.Logger logger) {
50 | return create(new AndroidQueueCache(), logger);
51 | }
52 |
53 | public static AndroidRxBus create(RxBus.QueueCache cache, RxBus.Logger logger) {
54 | return new AndroidRxBus(cache, logger);
55 | }
56 |
57 | private static final String TAG = AndroidRxBus.class.getSimpleName();
58 |
59 | private final Bus bus;
60 |
61 | private AndroidRxBus(RxBus.QueueCache cache, RxBus.Logger logger) {
62 | bus = RxBus.create(cache, logger);
63 | }
64 |
65 | @Override
66 | public void publish(Queue queue, T event) {
67 | bus.publish(queue, event);
68 | }
69 |
70 | @Override
71 | public Relay queue(Queue queue) {
72 | return bus.queue(queue);
73 | }
74 |
75 | @Override
76 | public Subscription subscribe(Queue queue, Observer observer) {
77 | return subscribe(queue, observer, AndroidSchedulers.mainThread());
78 | }
79 |
80 | @Override
81 | public Subscription subscribe(Queue queue, Observer observer, Scheduler scheduler) {
82 | return bus.subscribe(queue, observer, scheduler);
83 | }
84 |
85 | private static final class AndroidQueueCache implements RxBus.QueueCache {
86 |
87 | private final SparseArray> sparseArray = new SparseArray<>();
88 |
89 | @Override
90 | @SuppressWarnings("unchecked")
91 | public Relay get(Queue queue) {
92 | return (Relay) sparseArray.get(queue.getId());
93 | }
94 |
95 | @Override
96 | public void put(Queue queue, Relay relay) {
97 | sparseArray.put(queue.getId(), relay);
98 | }
99 | }
100 | }
--------------------------------------------------------------------------------
/rxbus/src/main/java/net/jokubasdargis/rxbus/Queue.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.concurrent.atomic.AtomicInteger;
20 |
21 | /**
22 | * A communication channel for specific event types.
23 | *
24 | * @param Type of event this queue supports.
25 | */
26 | @SuppressWarnings("WeakerAccess")
27 | public final class Queue {
28 |
29 | /**
30 | * Creates a builder of a {@link Queue} for the given event type.
31 | */
32 | public static Builder of(Class eventTypeClass) {
33 | return new Builder<>(eventTypeClass);
34 | }
35 |
36 | /**
37 | * A builder to build customized {@link Queue}s.
38 | */
39 | public static final class Builder {
40 |
41 | public Queue build() {
42 | if (name == null) {
43 | name = eventType.getSimpleName() + "Queue";
44 | }
45 |
46 | return new Queue<>(name, eventType, replayLast, defaultEvent);
47 | }
48 |
49 | public Builder name(String s) {
50 | name = s;
51 | return this;
52 | }
53 |
54 | public Builder replay() {
55 | replayLast = true;
56 | return this;
57 | }
58 |
59 | public Builder replay(T obj) {
60 | replayLast = true;
61 | defaultEvent = obj;
62 | return this;
63 | }
64 |
65 | private T defaultEvent;
66 | private final Class eventType;
67 | private String name;
68 | private boolean replayLast;
69 |
70 | Builder(Class eventTypeClass) {
71 | eventType = eventTypeClass;
72 | }
73 | }
74 |
75 | private static final AtomicInteger RUNNING_ID = new AtomicInteger();
76 |
77 | private final Class eventType;
78 | private final String name;
79 |
80 | private final int id;
81 | private final T defaultEvent;
82 | private final boolean replayLast;
83 |
84 | Queue(String s, Class eventTypeClass, boolean flag, T event) {
85 | name = s;
86 | eventType = eventTypeClass;
87 | replayLast = flag;
88 | defaultEvent = event;
89 | id = RUNNING_ID.incrementAndGet();
90 | }
91 |
92 | public Class getEventType() {
93 | return eventType;
94 | }
95 |
96 | public String getName() {
97 | return name;
98 | }
99 |
100 | int getId() {
101 | return id;
102 | }
103 |
104 | T getDefaultEvent() {
105 | return defaultEvent;
106 | }
107 |
108 | boolean isReplayLast() {
109 | return replayLast;
110 | }
111 |
112 | @Override
113 | public boolean equals(Object obj) {
114 | return (obj != null) && (obj instanceof Queue) && ((Queue) obj).id == id;
115 | }
116 |
117 | @Override
118 | public int hashCode() {
119 | return id;
120 | }
121 |
122 | @Override
123 | public String toString() {
124 | return name + "[" + eventType.getCanonicalName() + "]";
125 | }
126 | }
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/DefaultDispatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.Map;
20 | import java.util.concurrent.ConcurrentHashMap;
21 | import rx.Scheduler;
22 | import rx.Subscriber;
23 | import rx.Subscription;
24 |
25 | final class DefaultDispatcher implements Dispatcher {
26 |
27 | private final Map, Subscription> subscriptions = new ConcurrentHashMap<>(8);
28 |
29 | private final Bus bus;
30 | private final Scheduler busScheduler;
31 | private final Flusher flusher;
32 | private final ErrorListener errorListener;
33 |
34 | static Dispatcher create(Bus bus, Scheduler scheduler, Flusher flusher,
35 | ErrorListener errorListener) {
36 | return new DefaultDispatcher(bus, scheduler, flusher, errorListener);
37 | }
38 |
39 | @Override
40 | public void publish(Queue queue, T event) {
41 | bus.publish(queue, event);
42 | }
43 |
44 | @Override
45 | public void register(Queue queue, Station station) {
46 | synchronized (subscriptions) {
47 | if (!subscriptions.containsKey(station)) {
48 | subscriptions.put(station, bus.subscribe(
49 | queue, new StationSubscriber<>(station, flusher, errorListener), busScheduler));
50 | }
51 | }
52 | }
53 |
54 | @Override
55 | public void unregister(Station station) {
56 | Subscription subscription = subscriptions.remove(station);
57 | if (subscription != null) {
58 | subscription.unsubscribe();
59 | }
60 | }
61 |
62 | private static class StationSubscriber extends Subscriber {
63 |
64 | private final Station station;
65 | private final Flusher flusher;
66 | private final ErrorListener errorListener;
67 |
68 | StationSubscriber(Station station, Flusher flusher, ErrorListener errorListener) {
69 | this.station = station;
70 | this.flusher = flusher;
71 | this.errorListener = errorListener;
72 | }
73 |
74 | @Override
75 | public void onCompleted() {
76 | // no-op
77 | }
78 |
79 | @Override
80 | public void onError(Throwable e) {
81 | // no-op
82 | }
83 |
84 | @Override
85 | public void onNext(T t) {
86 | try {
87 | station.receive(t);
88 | } catch (Throwable throwable) {
89 | // We want to continue using this subscriber even if the receiver throws
90 | // so we just pass the error to a dedicated handler
91 | errorListener.onError(throwable);
92 | } finally {
93 | flusher.schedule(station);
94 | }
95 | }
96 |
97 | @Override
98 | public String toString() {
99 | return "StationSubscriber{"
100 | + "station=" + station
101 | + '}';
102 | }
103 | }
104 |
105 | private DefaultDispatcher(Bus bus, Scheduler busScheduler, Flusher flusher,
106 | ErrorListener errorListener) {
107 | this.bus = bus;
108 | this.busScheduler = busScheduler;
109 | this.flusher = flusher;
110 | this.errorListener = errorListener;
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/main/java/net/jokubasdargis/rxbus/RxBusDispatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import java.util.concurrent.TimeUnit;
20 | import rx.Scheduler;
21 | import rx.schedulers.Schedulers;
22 |
23 | @SuppressWarnings("WeakerAccess")
24 | public final class RxBusDispatcher {
25 |
26 | public static Builder builder() {
27 | return new Builder();
28 | }
29 |
30 | public static final class Builder {
31 |
32 | private static final long DEFAULT_FLUSH_DELAY_MIN = 2;
33 |
34 | private Bus bus;
35 | private Scheduler busScheduler;
36 | private Scheduler flushScheduler;
37 | private long flushDelay;
38 | private TimeUnit flushDelayTimeUnit;
39 | private ErrorListener errorListener;
40 |
41 | Builder() {
42 | }
43 |
44 | public Builder bus(Bus bus) {
45 | if (bus == null) {
46 | throw new NullPointerException("bus == null");
47 | }
48 | this.bus = bus;
49 | return this;
50 | }
51 |
52 | public Builder busScheduler(Scheduler scheduler) {
53 | if (scheduler == null) {
54 | throw new NullPointerException("scheduler == null");
55 | }
56 | this.busScheduler = scheduler;
57 | return this;
58 | }
59 |
60 | public Builder flushScheduler(Scheduler scheduler) {
61 | if (scheduler == null) {
62 | throw new NullPointerException("scheduler == null");
63 | }
64 | this.flushScheduler = scheduler;
65 | return this;
66 | }
67 |
68 | public Builder flushDelay(long flushDelay, TimeUnit timeUnit) {
69 | if (timeUnit == null) {
70 | throw new NullPointerException("timeUnit == null");
71 | }
72 | this.flushDelay = flushDelay;
73 | this.flushDelayTimeUnit = timeUnit;
74 | return this;
75 | }
76 |
77 | public Builder errorListener(ErrorListener errorListener) {
78 | if (errorListener == null) {
79 | throw new NullPointerException("errorListener == null");
80 | }
81 | this.errorListener = errorListener;
82 | return this;
83 | }
84 |
85 | public Dispatcher build() {
86 | if (bus == null) {
87 | bus = RxBus.create();
88 | }
89 |
90 | if (busScheduler == null) {
91 | busScheduler = Schedulers.immediate();
92 | }
93 |
94 | if (flushScheduler == null) {
95 | flushScheduler = Schedulers.io();
96 | }
97 |
98 | if (flushDelayTimeUnit == null) {
99 | flushDelay = DEFAULT_FLUSH_DELAY_MIN;
100 | flushDelayTimeUnit = TimeUnit.MINUTES;
101 | }
102 |
103 | if (errorListener == null) {
104 | errorListener = ErrorListener.NOOP;
105 | }
106 |
107 | return DefaultDispatcher.create(bus, busScheduler,
108 | DefaultFlusher.create(flushScheduler, flushDelay,
109 | flushDelayTimeUnit),
110 | errorListener);
111 | }
112 | }
113 |
114 | private RxBusDispatcher() {
115 | throw new AssertionError("No instances");
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/gradle/mvn-push.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven'
2 | apply plugin: 'signing'
3 |
4 | def isReleaseBuild() {
5 | return VERSION_NAME.contains('SNAPSHOT') == false
6 | }
7 |
8 | def getReleaseRepositoryUrl() {
9 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL
10 | : "https://oss.sonatype.org/content/repositories/snapshots/"
11 | }
12 |
13 | def getSnapshotRepositoryUrl() {
14 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL
15 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
16 | }
17 |
18 | def getRepositoryUsername() {
19 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
20 | }
21 |
22 | def getRepositoryPassword() {
23 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
24 | }
25 |
26 | afterEvaluate { project ->
27 | uploadArchives {
28 | repositories {
29 | mavenDeployer {
30 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
31 |
32 | pom.groupId = GROUP
33 | pom.artifactId = POM_ARTIFACT_ID
34 | pom.version = VERSION_NAME
35 |
36 | repository(url: getReleaseRepositoryUrl()) {
37 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
38 | }
39 | snapshotRepository(url: getSnapshotRepositoryUrl()) {
40 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
41 | }
42 |
43 | pom.project {
44 | name POM_NAME
45 | packaging POM_PACKAGING
46 | description POM_DESCRIPTION
47 | url POM_URL
48 |
49 | scm {
50 | url POM_SCM_URL
51 | connection POM_SCM_CONNECTION
52 | developerConnection POM_SCM_DEV_CONNECTION
53 | }
54 |
55 | licenses {
56 | license {
57 | name POM_LICENCE_NAME
58 | url POM_LICENCE_URL
59 | distribution POM_LICENCE_DIST
60 | }
61 | }
62 |
63 | developers {
64 | developer {
65 | id POM_DEVELOPER_ID
66 | name POM_DEVELOPER_NAME
67 | }
68 | }
69 | }
70 | }
71 | }
72 | }
73 |
74 | signing {
75 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
76 | sign configurations.archives
77 | }
78 |
79 | if (plugins.hasPlugin('com.android.library')) {
80 | task androidJavadocs(type: Javadoc) {
81 | failOnError = false
82 | source = android.sourceSets.main.java.srcDirs
83 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
84 | exclude '**/internal/*'
85 |
86 | if (JavaVersion.current().isJava8Compatible()) {
87 | options.addStringOption('Xdoclint:none', '-quiet')
88 | }
89 | }
90 |
91 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
92 | classifier = 'javadoc'
93 | from androidJavadocs.destinationDir
94 | }
95 |
96 | task androidSourcesJar(type: Jar) {
97 | classifier = 'sources'
98 | from android.sourceSets.main.java.sourceFiles
99 | }
100 |
101 | artifacts {
102 | archives androidSourcesJar
103 | archives androidJavadocsJar
104 | }
105 | } else {
106 | javadoc {
107 | if (JavaVersion.current().isJava8Compatible()) {
108 | options.addStringOption('Xdoclint:none', '-quiet')
109 | }
110 | }
111 |
112 | task javadocJar(type: Jar, dependsOn: javadoc) {
113 | classifier 'javadoc'
114 | from "$buildDir/docs/javadoc"
115 | }
116 |
117 | task sourcesJar(type: Jar) {
118 | classifier = 'sources'
119 | from sourceSets.main.allSource
120 | }
121 |
122 | artifacts {
123 | archives sourcesJar
124 | archives javadocJar
125 | }
126 | }
127 | }
128 |
129 |
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/rxbus/src/test/java/net/jokubasdargis/rxbus/RxBusTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.Relay;
20 |
21 | import static org.junit.Assert.assertEquals;
22 | import static org.junit.Assert.assertNotNull;
23 | import static org.mockito.Matchers.anyString;
24 | import static org.mockito.Mockito.never;
25 | import static org.mockito.Mockito.spy;
26 | import static org.mockito.Mockito.verify;
27 |
28 | import java.util.ArrayList;
29 | import java.util.List;
30 | import java.util.concurrent.atomic.AtomicInteger;
31 |
32 | import org.junit.Test;
33 |
34 | import rx.Observer;
35 | import rx.Subscription;
36 | import rx.subscriptions.CompositeSubscription;
37 |
38 | public final class RxBusTest {
39 |
40 | private final Queue events = Queue.of(Event.class).name("TestQueue").build();
41 |
42 | @Test
43 | public void queueAsRelay() {
44 | Bus bus = RxBus.create();
45 | Relay relay = bus.queue(events);
46 | assertNotNull(relay);
47 | }
48 |
49 | @Test
50 | public void publishEvent() {
51 | Bus bus = RxBus.create();
52 | Observer observer = spy(new PrintingObserver());
53 | Subscription subscription = bus.subscribe(events, observer);
54 | Event event = Event.create();
55 | bus.publish(events, event);
56 | subscription.unsubscribe();
57 | verify(observer).onNext(event);
58 | verify(observer, never()).onCompleted();
59 | }
60 |
61 | @Test
62 | public void loggerLogs() {
63 | RxBus.Logger logger = spy(new RxBus.Logger() {
64 | @Override
65 | public void log(String message) {
66 | System.out.println(message);
67 | }
68 | });
69 | Bus bus = RxBus.create(logger);
70 | bus.publish(events, Event.create());
71 | verify(logger).log(anyString());
72 | }
73 |
74 | @Test
75 | public void oneQueueMultipleObservers() {
76 | Bus bus = RxBus.create();
77 | CompositeSubscription subscriptions = new CompositeSubscription();
78 | List> observers = new ArrayList<>();
79 | for (int i = 0; i < 100; i++) {
80 | Observer observer = spy(new NoopObserver());
81 | observers.add(observer);
82 | subscriptions.add(bus.subscribe(events, observer));
83 | }
84 | Event event = Event.create();
85 | bus.publish(events, event);
86 | subscriptions.unsubscribe();
87 | for (Observer observer : observers) {
88 | verify(observer).onNext(event);
89 | }
90 | }
91 |
92 | @Test
93 | public void allEventsGoThrough() {
94 | final int numEvents = 1000;
95 | Bus bus = RxBus.create();
96 | CountingObserver observer = new CountingObserver();
97 | Subscription subscription = bus.subscribe(events, observer);
98 | for (int i = 0; i < numEvents; i++) {
99 | bus.publish(events, Event.create());
100 | }
101 | subscription.unsubscribe();
102 | assertEquals(numEvents, observer.getCount());
103 | }
104 |
105 | private static class PrintingObserver implements Observer {
106 | @Override
107 | public void onCompleted() {
108 | System.out.println("onComplete() called");
109 | }
110 |
111 | @Override
112 | public void onError(Throwable e) {
113 | System.out.println("onError() called with " + e);
114 | }
115 |
116 | @Override
117 | public void onNext(V v) {
118 | System.out.println("onNext() called with " + v);
119 | }
120 | }
121 |
122 | private static class CountingObserver implements Observer {
123 |
124 | private final AtomicInteger count = new AtomicInteger();
125 |
126 | @Override
127 | public void onCompleted() {
128 | }
129 |
130 | @Override
131 | public void onError(Throwable e) {
132 | throw new RuntimeException(e);
133 | }
134 |
135 | @Override
136 | public void onNext(Event event) {
137 | count.incrementAndGet();
138 | }
139 |
140 | int getCount() {
141 | return count.get();
142 | }
143 | }
144 |
145 | private static class NoopObserver implements Observer {
146 | @Override
147 | public void onCompleted() {
148 | }
149 |
150 | @Override
151 | public void onError(Throwable e) {
152 | }
153 |
154 | @Override
155 | public void onNext(V v) {
156 | }
157 | }
158 | }
159 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/rxbus-dispatcher/src/test/java/net/jokubasdargis/rxbus/DefaultDispatcherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import static org.mockito.Matchers.any;
20 | import static org.mockito.Mockito.doAnswer;
21 | import static org.mockito.Mockito.mock;
22 | import static org.mockito.Mockito.times;
23 | import static org.mockito.Mockito.verify;
24 | import static org.mockito.Mockito.verifyNoMoreInteractions;
25 |
26 | import java.util.concurrent.atomic.AtomicBoolean;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 | import org.mockito.invocation.InvocationOnMock;
30 | import org.mockito.stubbing.Answer;
31 | import rx.schedulers.Schedulers;
32 | import rx.schedulers.TestScheduler;
33 |
34 | @SuppressWarnings("unchecked")
35 | public final class DefaultDispatcherTest {
36 |
37 | private final EventA eventA = new EventA();
38 | private final Queue queue = Queue.of(EventA.class).build();
39 | private final Bus bus = RxBus.create();
40 | private final Station stationA1 = mock(Station.class);
41 | private final Station stationA2 = mock(Station.class);
42 | private final Flusher flusher = mock(Flusher.class);
43 | private final ErrorListener errorListener = mock(ErrorListener.class);
44 | private final TestScheduler scheduler = Schedulers.test();
45 | private final Dispatcher dispatcher = DefaultDispatcher.create(
46 | bus, scheduler, flusher, errorListener);
47 |
48 | @Before
49 | public void setUp() {
50 | doAnswer(new Answer() {
51 | @Override
52 | public Object answer(InvocationOnMock invocation) throws Throwable {
53 | Station station = (Station) invocation.getArguments()[0];
54 | station.flush();
55 | return null;
56 | }
57 | }).when(flusher).schedule(any(Station.class));
58 | }
59 |
60 | @Test
61 | public void singleStationSingleEvent() {
62 | dispatcher.register(queue, stationA1);
63 | dispatcher.publish(queue, eventA);
64 | scheduler.triggerActions();
65 |
66 | verify(stationA1).receive(eventA);
67 | verify(stationA1).flush();
68 |
69 | verifyNoMoreInteractions(stationA1);
70 | }
71 |
72 | @Test
73 | public void multipleStationSingleEvent() {
74 | dispatcher.register(queue, stationA1);
75 | dispatcher.register(queue, stationA2);
76 | dispatcher.publish(queue, eventA);
77 | scheduler.triggerActions();
78 |
79 | verify(stationA1).receive(eventA);
80 | verify(stationA1).flush();
81 | verify(stationA2).receive(eventA);
82 | verify(stationA2).flush();
83 |
84 | verifyNoMoreInteractions(stationA1, stationA2);
85 |
86 | }
87 |
88 | @Test
89 | public void singleStationRegisterUnregister() {
90 | dispatcher.register(queue, stationA1);
91 | dispatcher.publish(queue, eventA);
92 | scheduler.triggerActions();
93 | dispatcher.unregister(stationA1);
94 |
95 | verify(stationA1).receive(eventA);
96 | verify(stationA1).flush();
97 |
98 | dispatcher.publish(queue, eventA);
99 | scheduler.triggerActions();
100 |
101 | verifyNoMoreInteractions(stationA1);
102 | }
103 |
104 | @Test
105 | public void singleStationFlushWhenReceiveThrows() {
106 | final Throwable error = new RuntimeException();
107 | doAnswer(new Answer() {
108 | @Override
109 | public Object answer(InvocationOnMock invocation) throws Throwable {
110 | throw error;
111 | }
112 | }).when(stationA1).receive(eventA);
113 |
114 | dispatcher.register(queue, stationA1);
115 | dispatcher.publish(queue, eventA);
116 | scheduler.triggerActions();
117 |
118 | verify(stationA1).receive(eventA);
119 | verify(stationA1).flush();
120 | verify(errorListener).onError(error);
121 |
122 | verifyNoMoreInteractions(stationA1);
123 | verifyNoMoreInteractions(errorListener);
124 | }
125 |
126 | @Test
127 | public void singleStationReceiveAfterReceiveThrows() {
128 | final Throwable error = new RuntimeException();
129 | final AtomicBoolean thrown = new AtomicBoolean();
130 | doAnswer(new Answer() {
131 | @Override
132 | public Object answer(InvocationOnMock invocation) throws Throwable {
133 | if (thrown.compareAndSet(false, true)) {
134 | throw error;
135 | } else {
136 | return null;
137 | }
138 | }
139 | }).when(stationA1).receive(eventA);
140 |
141 | dispatcher.register(queue, stationA1);
142 | dispatcher.publish(queue, eventA);
143 | dispatcher.publish(queue, eventA);
144 | scheduler.triggerActions();
145 |
146 | verify(stationA1, times(2)).receive(eventA);
147 | verify(stationA1, times(2)).flush();
148 | verify(errorListener).onError(error);
149 |
150 | verifyNoMoreInteractions(stationA1);
151 | verifyNoMoreInteractions(errorListener);
152 | }
153 |
154 | }
155 |
--------------------------------------------------------------------------------
/rxbus-android/src/test/java/net/jokubasdargis/rxbus/AndroidRxBusTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.Relay;
20 |
21 | import org.junit.Test;
22 |
23 | import java.util.ArrayList;
24 | import java.util.List;
25 | import java.util.concurrent.atomic.AtomicInteger;
26 |
27 | import rx.Observer;
28 | import rx.Subscription;
29 | import rx.schedulers.Schedulers;
30 | import rx.schedulers.TestScheduler;
31 | import rx.subscriptions.CompositeSubscription;
32 |
33 | import static org.junit.Assert.assertEquals;
34 | import static org.junit.Assert.assertNotNull;
35 | import static org.mockito.Mockito.never;
36 | import static org.mockito.Mockito.spy;
37 | import static org.mockito.Mockito.verify;
38 |
39 | public final class AndroidRxBusTest {
40 |
41 | private final static RxBus.Logger SYSTEM_LOGGER = new RxBus.Logger() {
42 | @Override
43 | public void log(String message) {
44 | System.out.println(message);
45 | }
46 | };
47 |
48 | private final Queue events = Queue.of(Event.class).name("TestQueue").build();
49 | private final RxBus.QueueCache queueCache = new RxBus.DefaultQueueCache();
50 | private final TestScheduler testScheduler = Schedulers.test();
51 |
52 | @Test
53 | public void create() {
54 | Bus bus = AndroidRxBus.create();
55 | assertNotNull(bus);
56 | }
57 |
58 | @Test
59 | public void createWithLogger() {
60 | Bus bus = AndroidRxBus.create(SYSTEM_LOGGER);
61 | assertNotNull(bus);
62 | }
63 |
64 | @Test
65 | public void queueAsRelay() {
66 | Bus bus = AndroidRxBus.create(queueCache, SYSTEM_LOGGER);
67 | Relay relay = bus.queue(events);
68 | assertNotNull(relay);
69 | }
70 |
71 | @Test
72 | public void publishEvent() {
73 | Bus bus = AndroidRxBus.create(queueCache, SYSTEM_LOGGER);
74 | Observer observer = spy(new PrintingObserver());
75 | Subscription subscription = bus.subscribe(events, observer, testScheduler);
76 | Event event = Event.create();
77 | bus.publish(events, event);
78 | testScheduler.triggerActions();
79 | subscription.unsubscribe();
80 | verify(observer).onNext(event);
81 | verify(observer, never()).onCompleted();
82 | }
83 |
84 | @Test
85 | public void oneQueueMultipleObservers() {
86 | Bus bus = AndroidRxBus.create(queueCache, SYSTEM_LOGGER);
87 | CompositeSubscription subscriptions = new CompositeSubscription();
88 | List> observers = new ArrayList<>();
89 | for (int i = 0; i < 100; i++) {
90 | Observer observer = spy(new NoopObserver());
91 | observers.add(observer);
92 | subscriptions.add(bus.subscribe(events, observer, testScheduler));
93 | }
94 | Event event = Event.create();
95 | bus.publish(events, event);
96 | testScheduler.triggerActions();
97 | subscriptions.unsubscribe();
98 | for (Observer observer : observers) {
99 | verify(observer).onNext(event);
100 | }
101 | }
102 |
103 | @Test
104 | public void allEventsGoThrough() {
105 | final int numEvents = 100;
106 | Bus bus = AndroidRxBus.create(queueCache, SYSTEM_LOGGER);
107 | CountingObserver observer = new CountingObserver();
108 | Subscription subscription = bus.queue(events)
109 | .onBackpressureBuffer()
110 | .observeOn(testScheduler)
111 | .subscribe(observer);
112 | for (int i = 0; i < numEvents; i++) {
113 | bus.publish(events, Event.create());
114 | }
115 | testScheduler.triggerActions();
116 | subscription.unsubscribe();
117 | assertEquals(numEvents, observer.getCount());
118 | }
119 |
120 | private static class PrintingObserver implements Observer {
121 |
122 | @Override
123 | public void onCompleted() {
124 | System.out.println("onComplete() called");
125 | }
126 |
127 | @Override
128 | public void onError(Throwable e) {
129 | System.out.println("onError() called with " + e);
130 | }
131 |
132 | @Override
133 | public void onNext(V v) {
134 | System.out.println("onNext() called with " + v);
135 | }
136 | }
137 |
138 | private static class CountingObserver implements Observer {
139 |
140 | private final AtomicInteger count = new AtomicInteger();
141 |
142 | @Override
143 | public void onCompleted() {
144 | }
145 |
146 | @Override
147 | public void onError(Throwable e) {
148 | throw new RuntimeException(e);
149 | }
150 |
151 | @Override
152 | public void onNext(Event event) {
153 | count.incrementAndGet();
154 | }
155 |
156 | int getCount() {
157 | return count.get();
158 | }
159 | }
160 |
161 | private static class NoopObserver implements Observer {
162 |
163 | @Override
164 | public void onCompleted() {
165 | }
166 |
167 | @Override
168 | public void onError(Throwable e) {
169 | }
170 |
171 | @Override
172 | public void onNext(V v) {
173 | }
174 | }
175 | }
176 |
--------------------------------------------------------------------------------
/rxbus/src/main/java/net/jokubasdargis/rxbus/RxBus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Jokubas Dargis.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.jokubasdargis.rxbus;
18 |
19 | import com.jakewharton.rxrelay.Relay;
20 |
21 | import java.lang.ref.Reference;
22 | import java.lang.ref.WeakReference;
23 | import java.util.Collections;
24 | import java.util.HashMap;
25 | import java.util.Iterator;
26 | import java.util.LinkedList;
27 | import java.util.List;
28 | import java.util.Map;
29 | import java.util.WeakHashMap;
30 |
31 | import rx.Observer;
32 | import rx.Scheduler;
33 | import rx.Subscription;
34 | import rx.schedulers.Schedulers;
35 |
36 | /**
37 | * A basic implementation of {@link Bus} with {@link Queue} caching and logging capabilities.
38 | */
39 | @SuppressWarnings("WeakerAccess")
40 | public final class RxBus implements Bus {
41 |
42 | /**
43 | * Creates a new instance of {@link Bus} configured with a default {@link QueueCache}.
44 | */
45 | public static Bus create() {
46 | return create(new DefaultQueueCache());
47 | }
48 |
49 | /**
50 | * Creates a new instance of {@link Bus} configured with the given {@link QueueCache}.
51 | */
52 | public static Bus create(QueueCache cache) {
53 | return create(cache, null);
54 | }
55 |
56 | /**
57 | * Creates a new instance of {@link Bus} configured with the given {@link Logger}.
58 | */
59 | public static Bus create(Logger logger) {
60 | return create(new DefaultQueueCache(), logger);
61 | }
62 |
63 | /**
64 | * Creates a new instance of {@link Bus} configured with the given {@link QueueCache}
65 | * and {@link Logger}.
66 | */
67 | public static Bus create(QueueCache cache, Logger logger) {
68 | return new RxBus(cache, logger);
69 | }
70 |
71 | /**
72 | * Classes implementing this interface log debug messages from the {@link RxBus}.
73 | */
74 | public interface Logger {
75 | void log(String message);
76 | }
77 |
78 | /**
79 | * Classes implementing this interface provide a cache of {@link Relay}s associated to
80 | * {@link Queue}s used by the {@link RxBus}.
81 | */
82 | public interface QueueCache {
83 | Relay get(Queue queue);
84 |
85 | void put(Queue queue, Relay relay);
86 | }
87 |
88 | private final QueueCache cache;
89 | private final Logger logger;
90 | private final Map>>> loggedObservers;
91 |
92 | private RxBus(QueueCache cache, Logger logger) {
93 | if (cache == null) {
94 | throw new IllegalArgumentException("cache cannot be null");
95 | }
96 | this.cache = cache;
97 | this.logger = logger;
98 | this.loggedObservers = this.logger != null
99 | ? new HashMap>>>() : null;
100 | }
101 |
102 | /**
103 | * {@inheritDoc}
104 | */
105 | @Override
106 | public void publish(Queue queue, T event) {
107 | if (shouldLog()) {
108 | logEvent(queue, event);
109 | }
110 | queue(queue).call(event);
111 | }
112 |
113 | /**
114 | * {@inheritDoc}
115 | */
116 | @Override
117 | public Relay queue(Queue queue) {
118 | Relay relay = cache.get(queue);
119 | if (relay == null) {
120 | if (queue.getDefaultEvent() != null) {
121 | relay = ReplayEventRelay.create(queue.getDefaultEvent());
122 | } else if (queue.isReplayLast()) {
123 | relay = ReplayEventRelay.create();
124 | } else {
125 | relay = DefaultEventRelay.create();
126 | }
127 | cache.put(queue, relay);
128 | }
129 | return relay;
130 | }
131 |
132 | /**
133 | * {@inheritDoc}
134 | */
135 | @Override
136 | public Subscription subscribe(Queue queue, Observer observer) {
137 | return subscribe(queue, observer, Schedulers.immediate());
138 | }
139 |
140 | /**
141 | * {@inheritDoc}
142 | */
143 | @Override
144 | public Subscription subscribe(Queue queue, Observer observer, Scheduler scheduler) {
145 | if (shouldLog()) {
146 | registerObserver(queue, observer);
147 | }
148 | return queue(queue).observeOn(scheduler).subscribe(observer);
149 | }
150 |
151 | private boolean shouldLog() {
152 | return logger != null && loggedObservers != null;
153 | }
154 |
155 | @SuppressWarnings("unchecked")
156 | private void registerObserver(Queue queue, Observer observer) {
157 | List observers = (List) loggedObservers.get(queue.getId());
158 | if (observers == null) {
159 | observers = new LinkedList<>();
160 | loggedObservers.put(queue.getId(), observers);
161 | }
162 | observers.add(new WeakReference<>(observer));
163 | }
164 |
165 | private void logEvent(Queue queue, Object obj) {
166 | StringBuilder stringBuilder = new StringBuilder();
167 | stringBuilder.append("Publishing to ").append(queue.getName());
168 | stringBuilder.append(" [").append(obj).append("]\n");
169 | List list = loggedObservers.get(queue.getId());
170 | if (list != null && !list.isEmpty()) {
171 | stringBuilder.append("Delivering to: \n");
172 | Iterator iterator = list.iterator();
173 | do {
174 | if (!iterator.hasNext()) {
175 | break;
176 | }
177 | Observer observer = (Observer) ((Reference) iterator.next()).get();
178 | if (observer != null) {
179 | stringBuilder
180 | .append("-> ")
181 | .append(observer.getClass().getCanonicalName())
182 | .append('\n');
183 | }
184 | } while (true);
185 | } else {
186 | stringBuilder.append("No observers found.");
187 | }
188 | logger.log(stringBuilder.toString());
189 | }
190 |
191 | static final class DefaultQueueCache implements QueueCache {
192 |
193 | private final Map, Relay, ?>> map
194 | = Collections.synchronizedMap(new WeakHashMap, Relay, ?>>());
195 |
196 | @Override
197 | @SuppressWarnings("unchecked")
198 | public Relay get(Queue queue) {
199 | return (Relay) map.get(queue);
200 | }
201 |
202 | @Override
203 | public void put(Queue queue, Relay relay) {
204 | map.put(queue, relay);
205 | }
206 | }
207 | }
208 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or /*
187 | * name
188 | *
189 | * Created by eleventigers on 26/06/15 11:21.
190 | * Copyright (c) 2015 Obvious Engineering. All rights reserved.
191 | */
192 |
193 | class name and description of purpose be included on the
194 | same "printed page" as the copyright notice for easier
195 | identification within third-party archives.
196 |
197 | Copyright [yyyy] [name of copyright owner]
198 |
199 | Licensed under the Apache License, Version 2.0 (the "License");
200 | you may not use this file except in compliance with the License.
201 | You may obtain a copy of the License at
202 |
203 | http://www.apache.org/licenses/LICENSE-2.0
204 |
205 | Unless required by applicable law or agreed to in writing, software
206 | distributed under the License is distributed on an "AS IS" BASIS,
207 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
208 | See the License for the specific language governing permissions and
209 | limitations under the License.
--------------------------------------------------------------------------------