├── core
├── .gitignore
├── src
│ ├── main
│ │ └── java
│ │ │ └── com
│ │ │ └── lsxiao
│ │ │ └── apollo
│ │ │ └── core
│ │ │ ├── annotations
│ │ │ ├── Receive.kt
│ │ │ ├── Backpressure.kt
│ │ │ ├── Take.kt
│ │ │ ├── Sticky.kt
│ │ │ ├── ObserveOn.kt
│ │ │ └── SubscribeOn.kt
│ │ │ ├── serialize
│ │ │ ├── Serializable.kt
│ │ │ └── KryoSerializer.kt
│ │ │ ├── contract
│ │ │ ├── ApolloBinder.kt
│ │ │ └── ApolloBinderGenerator.kt
│ │ │ ├── ProcessUtil.kt
│ │ │ ├── entity
│ │ │ ├── ApolloBinderImpl.kt
│ │ │ ├── SchedulerProvider.kt
│ │ │ └── Event.java
│ │ │ └── Apollo.kt
│ └── test
│ │ └── java
│ │ └── com
│ │ └── lsxiao
│ │ └── apollo
│ │ └── core
│ │ └── KryoSerializeTest.java
└── build.gradle
├── demo
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ ├── dialog_subscriber.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── fragment_subscriber.xml
│ │ │ └── fragment_producer.xml
│ │ ├── java
│ │ └── com
│ │ │ └── lsxiao
│ │ │ └── apollo
│ │ │ └── demo
│ │ │ ├── App.java
│ │ │ ├── constant
│ │ │ └── Event.java
│ │ │ ├── model
│ │ │ └── User.java
│ │ │ ├── base
│ │ │ ├── BaseActivity.java
│ │ │ ├── BaseFragment.java
│ │ │ └── BaseDialogFragment.java
│ │ │ ├── TestService.java
│ │ │ ├── fragment
│ │ │ ├── SubscriberDialogFragment.java
│ │ │ ├── SubscriberFragment.java
│ │ │ └── ProducerFragment.java
│ │ │ └── TestActivity.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── ipc
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── lsxiao
│ │ └── apollo
│ │ └── ipc
│ │ └── ApolloProcessEventReceiver.java
├── build.gradle
└── proguard-rules.pro
├── processor
├── .gitignore
├── src
│ ├── main
│ │ └── java
│ │ │ └── com
│ │ │ └── lsxiao
│ │ │ └── apllo
│ │ │ └── processor
│ │ │ ├── Util.kt
│ │ │ ├── step
│ │ │ ├── TakeStep.kt
│ │ │ ├── StickyStep.kt
│ │ │ ├── ObserveStep.kt
│ │ │ ├── ReceiveStep.kt
│ │ │ ├── SubscribeStep.kt
│ │ │ └── BackpressureStep.kt
│ │ │ ├── ApolloDescriptor.kt
│ │ │ ├── ApolloProcessor.java
│ │ │ └── CodeGenerator.kt
│ └── test
│ │ └── java
│ │ └── ProcessUtilTest.kt
└── build.gradle
├── unittest
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── lsxiao
│ │ │ │ └── apollo
│ │ │ │ └── unittest
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── lsxiao
│ │ └── apollo
│ │ └── unittest
│ │ ├── BasicTest.java
│ │ └── BusTest.java
├── proguard-rules.pro
└── build.gradle
├── _config.yml
├── demo.gif
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── config
└── dependencies.gradle
├── gradlew.bat
├── gradlew
├── README-EN.md
├── README.md
└── LICENSE
/core/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/ipc/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/processor/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/unittest/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':processor', ':demo', ':core', ':ipc', ':unittest'
2 |
--------------------------------------------------------------------------------
/ipc/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/unittest/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | unittest
3 |
4 |
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sloaix/Apollo/HEAD/unittest/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/demo/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/unittest/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/Util.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor
2 |
3 | object Util {
4 | fun split(list: List, separator: String): String {
5 | return list.mapTo(ArrayList()) { "\"$it\"" }.joinToString(separator)
6 | }
7 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 11 21:10:58 CST 2017
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-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/unittest/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/Receive.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | /**
4 | * author lsxiao
5 | * date 2016-08-07 18:14
6 | */
7 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
8 | @kotlin.annotation.Retention
9 | annotation class Receive(vararg val value: String)
10 |
--------------------------------------------------------------------------------
/ipc/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 |
4 | group = 'com.github.lsxiao'
5 | android {
6 | def config = parent.ext
7 |
8 | compileSdkVersion config.compileSdkVersion
9 | buildToolsVersion config.buildToolsVersion
10 | }
11 |
12 | dependencies {
13 | compile project(':core')
14 | }
15 |
--------------------------------------------------------------------------------
/demo/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/Backpressure.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | import io.reactivex.BackpressureStrategy
4 |
5 | /**
6 | * write with Apollo
7 | * author:lsxiao
8 | * date:2017-04-22 03:00
9 | * github:https://github.com/lsxiao
10 | * zhihu:https://zhihu.com/people/lsxiao
11 | */
12 |
13 | annotation class Backpressure(val value: BackpressureStrategy)
14 |
--------------------------------------------------------------------------------
/unittest/src/main/java/com/lsxiao/apollo/unittest/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.unittest
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 |
6 | class MainActivity : AppCompatActivity() {
7 |
8 | override fun onCreate(savedInstanceState: Bundle?) {
9 | super.onCreate(savedInstanceState)
10 | setContentView(R.layout.activity_main)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/serialize/Serializable.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.serialize
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-05-17 17:23
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 |
11 | interface Serializable {
12 | fun serialize(obj: Any): ByteArray
13 |
14 | fun deserialize(data: ByteArray, clazz: Class): T
15 | }
16 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/unittest/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/Take.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-04-22 02:20
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
11 | @kotlin.annotation.Retention
12 | annotation class Take(val value: Int)
13 |
14 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/Sticky.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-04-22 02:20
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
11 | @kotlin.annotation.Retention
12 | annotation class Sticky(val remove: Boolean = true)
13 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/contract/ApolloBinder.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.contract
2 |
3 | import io.reactivex.disposables.Disposable
4 |
5 | /**
6 | * write with Apollo
7 | * author:lsxiao
8 | * date:2017-02-15 22:23
9 | * github:https://github.com/lsxiao
10 | * zhihu:https://zhihu.com/people/lsxiao
11 | */
12 |
13 | interface ApolloBinder {
14 | fun add(disposable: Disposable)
15 |
16 | fun unbind()
17 |
18 | fun isUnbind(): Boolean
19 | }
20 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/contract/ApolloBinderGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.contract
2 |
3 | import com.lsxiao.apollo.core.entity.Event
4 |
5 | /**
6 | * write with Apollo
7 | * author:lsxiao
8 | * date:2017-02-15 22:21
9 | * github:https://github.com/lsxiao
10 | * zhihu:https://zhihu.com/people/lsxiao
11 | */
12 |
13 | interface ApolloBinderGenerator {
14 | fun generate(subscriber: Any): ApolloBinder
15 |
16 | fun broadcastEvent(event: Event)
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/core/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply plugin: 'kotlin'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 |
5 | group = 'com.github.lsxiao'
6 | sourceCompatibility = 1.7
7 | targetCompatibility = 1.7
8 |
9 | dependencies {
10 | implementation fileTree(include: ['*.jar'], dir: 'libs')
11 | def test = parent.ext.test
12 | testImplementation test.junit
13 |
14 |
15 | def libs = parent.ext.libs
16 | compile libs.rxjava2
17 | compile libs.kotlin
18 | compile libs.kryo
19 | }
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/App.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo;
2 |
3 | import android.app.Application;
4 |
5 | import com.lsxiao.apollo.core.Apollo;
6 |
7 | import io.reactivex.android.schedulers.AndroidSchedulers;
8 |
9 |
10 | /**
11 | * author lsxiao
12 | * date 2016-08-08 13:33
13 | */
14 | public class App extends Application {
15 | @Override
16 | public void onCreate() {
17 | super.onCreate();
18 | Apollo.init(AndroidSchedulers.mainThread(), this, true);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/constant/Event.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.constant;
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-04-23 04:04
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 |
11 | public interface Event {
12 | String STR = "str";
13 | String INT_NUMBER = "int";
14 | String FLOAT_NUMBER = "float";
15 | String DOBLUE_NUMBER = "double";
16 | String BOOL = "bool";
17 | String OBJECT = "object";
18 | }
19 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ApolloDemo
3 | 第一activity
4 | 第二个activity
5 | 发送普通事件给第一个activity
6 | 发送sticky事件给第二个activity
7 | 移除第二个activity的sticky事件
8 | 启动第二个activity
9 |
10 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/ProcessUtil.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-05-15 16:56
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 |
11 | object ProcessUtil {
12 | /**
13 | * 使用反射的方式获取进程的id(Apollo是纯java库)
14 | */
15 | fun getPid(): Int {
16 | val threadClazz = Class.forName("android.os.Process")
17 | val method = threadClazz.getMethod("myPid")
18 | return method.invoke(null) as Int
19 | }
20 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/ObserveOn.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | import com.lsxiao.apollo.core.entity.SchedulerProvider
4 |
5 | /**
6 | * write with Apollo
7 | * author:lsxiao
8 | * date:2017-04-22 02:21
9 | * github:https://github.com/lsxiao
10 | * zhihu:https://zhihu.com/people/lsxiao
11 | */
12 |
13 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
14 | @kotlin.annotation.Retention
15 | annotation class ObserveOn(val value: SchedulerProvider.Tag = SchedulerProvider.Tag.MAIN)
16 |
--------------------------------------------------------------------------------
/processor/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 | apply plugin: 'kotlin'
3 | apply plugin: 'com.github.dcendents.android-maven'
4 |
5 | group = 'com.github.lsxiao'
6 | sourceCompatibility = 1.7
7 | targetCompatibility = 1.7
8 |
9 | dependencies {
10 | implementation fileTree(dir: 'libs', include: ['*.jar'])
11 | testImplementation parent.ext.test.junit
12 | def libs = parent.ext.libs
13 |
14 | compile project(':core')
15 | compile libs.javapoet
16 | compile libs.autoService
17 | compile libs.autoCommon
18 | compile libs.kotlin
19 | compile libs.rxjava2
20 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/annotations/SubscribeOn.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.annotations
2 |
3 | import com.lsxiao.apollo.core.entity.SchedulerProvider
4 |
5 |
6 | /**
7 | * write with Apollo
8 | * author:lsxiao
9 | * date:2017-04-22 02:21
10 | * github:https://github.com/lsxiao
11 | * zhihu:https://zhihu.com/people/lsxiao
12 | */
13 |
14 | @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
15 | @kotlin.annotation.Retention
16 | annotation class SubscribeOn(val value: SchedulerProvider.Tag = SchedulerProvider.Tag.IO)
17 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/model/User.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.model;
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-04-24 00:04
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 |
11 | public class User {
12 | String name;
13 |
14 | public User() {
15 | }
16 |
17 | public User(String name) {
18 | this.name = name;
19 | }
20 |
21 | @Override
22 | public String toString() {
23 | return "User{" +
24 | "name='" + name + '\'' +
25 | '}';
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 | gradle.properties
23 |
24 | # Proguard folder generated by Eclipse
25 | proguard/
26 |
27 | # Log Files
28 | *.log
29 |
30 | # Android Studio Navigation editor temp files
31 | .navigation/
32 |
33 | # Android Studio captures folder
34 | captures/
35 |
36 | # Intellij
37 | *.iml
38 |
39 | # Keystore files
40 | *.jks
41 |
42 | .DS_Store
43 | /captures
44 | .idea
--------------------------------------------------------------------------------
/demo/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/boluo/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/processor/src/test/java/ProcessUtilTest.kt:
--------------------------------------------------------------------------------
1 | import com.lsxiao.apllo.processor.Util
2 | import junit.framework.TestCase
3 | import org.junit.Test
4 | import java.util.*
5 |
6 | /**
7 | * write with Apollo
8 | * author:lsxiao
9 | * date:2017-04-23 11:24
10 | * github:https://github.com/lsxiao
11 | * zhihu:https://zhihu.com/people/lsxiao
12 | */
13 |
14 |
15 | class ProcessUtilTest : TestCase() {
16 | @Test
17 | fun testSplit() {
18 | assertEquals(""""a","b","c"""", Util.split(Arrays.asList("a", "b", "c"), ","))
19 |
20 | assertEquals(""""a","b"""", Util.split(Arrays.asList("a", "b"), ","))
21 |
22 | assertEquals(""""a"""", Util.split(Arrays.asList("a"), ","))
23 |
24 | assertEquals("", Util.split(Arrays.asList(), ","))
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/unittest/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/unittest/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/unittest/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/base/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.base;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 |
6 | import com.lsxiao.apollo.core.Apollo;
7 | import com.lsxiao.apollo.core.contract.ApolloBinder;
8 |
9 |
10 | public abstract class BaseActivity extends AppCompatActivity {
11 | private ApolloBinder mBinder;
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(getLayoutId());
17 | mBinder = Apollo.bind(this);
18 | afterCreate(savedInstanceState);
19 | }
20 |
21 | @Override
22 | protected void onDestroy() {
23 | super.onDestroy();
24 | mBinder.unbind();
25 | }
26 |
27 | protected abstract int getLayoutId();
28 |
29 | protected abstract void afterCreate(Bundle savedInstanceState);
30 | }
31 |
--------------------------------------------------------------------------------
/demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/ipc/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/boluo/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/TestService.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.IBinder;
6 | import android.os.Process;
7 | import android.support.annotation.Nullable;
8 |
9 | import com.lsxiao.apollo.core.Apollo;
10 | import com.lsxiao.apollo.demo.model.User;
11 |
12 | /**
13 | * write with Apollo
14 | * author:lsxiao
15 | * date:2017-05-15 15:18
16 | * github:https://github.com/lsxiao
17 | * zhihu:https://zhihu.com/people/lsxiao
18 | */
19 |
20 | public class TestService extends Service {
21 | public TestService() {
22 | super();
23 | }
24 |
25 | @Override
26 | public int onStartCommand(Intent intent, int flags, int startId) {
27 | Apollo.emit("ipc", new User("a User from TestService and pid is" + Process.myPid()));
28 | return super.onStartCommand(intent, flags, startId);
29 | }
30 |
31 | @Nullable
32 | @Override
33 | public IBinder onBind(Intent intent) {
34 | return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/entity/ApolloBinderImpl.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.entity
2 |
3 | import com.lsxiao.apollo.core.Apollo
4 | import com.lsxiao.apollo.core.contract.ApolloBinder
5 | import io.reactivex.disposables.CompositeDisposable
6 | import io.reactivex.disposables.Disposable
7 |
8 | /**
9 | * write with Apollo
10 | * author:lsxiao
11 | * date:2017-02-15 22:27
12 | * github:https://github.com/lsxiao
13 | * zhihu:https://zhihu.com/people/lsxiao
14 | */
15 |
16 | class ApolloBinderImpl(private val o: Any) : ApolloBinder {
17 | private val mCompositeDisposable: CompositeDisposable by lazy {
18 | CompositeDisposable()
19 | }
20 |
21 | override fun add(disposable: Disposable) {
22 | mCompositeDisposable.add(disposable)
23 | }
24 |
25 | override fun unbind() {
26 | if (!mCompositeDisposable.isDisposed) {
27 | mCompositeDisposable.clear()
28 | }
29 | Apollo.unBind(o)
30 | }
31 |
32 | override fun isUnbind(): Boolean {
33 | return mCompositeDisposable.isDisposed
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/demo/src/main/res/layout/dialog_subscriber.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
18 |
19 |
26 |
27 |
--------------------------------------------------------------------------------
/demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
20 |
21 |
28 |
29 |
34 |
35 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/TakeStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.Take
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloProcessor
8 | import java.util.*
9 | import javax.lang.model.element.Element
10 |
11 | /**
12 | * write with Apollo
13 | * author:lsxiao
14 | * date:2017-04-22 02:17
15 | * github:https://github.com/lsxiao
16 | * zhihu:https://zhihu.com/people/lsxiao
17 | */
18 |
19 | class TakeStep : BasicAnnotationProcessor.ProcessingStep {
20 | override fun annotations(): Set> = setOf(Take::class.java)
21 |
22 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
23 | elementsByAnnotation.asMap().keys.forEach { clazz ->
24 | elementsByAnnotation.asMap()[clazz]?.mapNotNull { ApolloProcessor.sDescriptorMap[it] }?.forEach {
25 | it.take = MoreElements.asExecutable(it.methodElement).getAnnotation(Take::class.java).value
26 | }
27 | }
28 | return HashSet()
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/ipc/src/main/java/com/lsxiao/apollo/ipc/ApolloProcessEventReceiver.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.ipc;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Process;
7 |
8 | import com.lsxiao.apollo.core.Apollo;
9 | import com.lsxiao.apollo.core.entity.Event;
10 |
11 |
12 | /**
13 | * write with Apollo
14 | * author:lsxiao
15 | * date:2017-05-15 14:28
16 | * github:https://github.com/lsxiao
17 | * zhihu:https://zhihu.com/people/lsxiao
18 | */
19 |
20 | public class ApolloProcessEventReceiver extends BroadcastReceiver {
21 | public static String KEY_EVENT = "event";
22 |
23 | @Override
24 | public void onReceive(Context context, Intent intent) {
25 | if (!intent.hasExtra(KEY_EVENT) || intent.getByteArrayExtra(KEY_EVENT) == null) {
26 | return;
27 | }
28 | Event event;
29 | try {
30 | event = Apollo.getSerializer().deserialize(intent.getByteArrayExtra(KEY_EVENT), Event.class);
31 | } catch (Exception e) {
32 | e.printStackTrace();
33 | return;
34 | }
35 |
36 | if (event.getPid() == Process.myPid()) {
37 | return;
38 | }
39 |
40 | Apollo.transfer(event);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/StickyStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.Sticky
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloProcessor
8 | import java.util.*
9 | import javax.lang.model.element.Element
10 |
11 | /**
12 | * write with Apollo
13 | * author:lsxiao
14 | * date:2017-04-22 02:17
15 | * github:https://github.com/lsxiao
16 | * zhihu:https://zhihu.com/people/lsxiao
17 | */
18 |
19 | class StickyStep : BasicAnnotationProcessor.ProcessingStep {
20 | override fun annotations(): Set> = setOf(Sticky::class.java)
21 |
22 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
23 | elementsByAnnotation.asMap().keys.forEach { clazz ->
24 | elementsByAnnotation.asMap()[clazz]?.mapNotNull { ApolloProcessor.sDescriptorMap[it] }?.forEach {
25 | it.isSticky = true
26 | it.stickyAutoRemove = MoreElements.asExecutable(it.methodElement).getAnnotation(Sticky::class.java).remove
27 | }
28 | }
29 | return HashSet()
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/ObserveStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.ObserveOn
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloProcessor
8 | import java.util.*
9 | import javax.lang.model.element.Element
10 |
11 | /**
12 | * write with Apollo
13 | * author:lsxiao
14 | * date:2017-04-22 02:17
15 | * github:https://github.com/lsxiao
16 | * zhihu:https://zhihu.com/people/lsxiao
17 | */
18 |
19 | class ObserveStep : BasicAnnotationProcessor.ProcessingStep {
20 | override fun annotations(): Set> = setOf(ObserveOn::class.java)
21 |
22 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
23 | elementsByAnnotation.asMap().keys.forEach {
24 | elementsByAnnotation.asMap()[it]?.forEach list@ {
25 | val descriptor = ApolloProcessor.sDescriptorMap[it] ?: return@list
26 |
27 | if (MoreElements.isAnnotationPresent(it, ObserveOn::class.java)) {
28 | descriptor.observeOn = MoreElements.asExecutable(it).getAnnotation(ObserveOn::class.java).value
29 | }
30 | }
31 | }
32 | return HashSet()
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/ApolloDescriptor.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor
2 |
3 | import com.lsxiao.apollo.core.entity.SchedulerProvider
4 | import io.reactivex.BackpressureStrategy
5 | import java.util.*
6 | import javax.lang.model.element.ExecutableElement
7 |
8 | /**
9 | * write with Apollo
10 | * author:lsxiao
11 | * date:2017-04-22 02:19
12 | * github:https://github.com/lsxiao
13 | * zhihu:https://zhihu.com/people/lsxiao
14 | */
15 |
16 | class ApolloDescriptor private constructor(val methodElement: ExecutableElement) {
17 | companion object {
18 | fun newInstance(methodElement: ExecutableElement): ApolloDescriptor {
19 | return ApolloDescriptor(methodElement)
20 | }
21 | }
22 |
23 | var isSticky = false
24 | var stickyAutoRemove = true
25 | var take = 0
26 | var tags: List = ArrayList()
27 | var subscribeOn = SchedulerProvider.Tag.IO
28 | var observeOn = SchedulerProvider.Tag.MAIN
29 | var backpressureStrategy: BackpressureStrategy? = null
30 |
31 | override fun equals(other: Any?): Boolean {
32 | if (this === other) return true
33 | if (other == null || javaClass != other.javaClass) return false
34 |
35 | val that = other as ApolloDescriptor?
36 |
37 | return methodElement == that!!.methodElement
38 |
39 | }
40 |
41 | override fun hashCode(): Int {
42 | return methodElement.hashCode()
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/entity/SchedulerProvider.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.entity
2 |
3 | import com.lsxiao.apollo.core.entity.SchedulerProvider.Tag.*
4 | import io.reactivex.Scheduler
5 | import io.reactivex.schedulers.Schedulers
6 |
7 |
8 | /**
9 | * write with Apollo
10 | * author:lsxiao
11 | * date:2017-02-15 22:32
12 | * github:https://github.com/lsxiao
13 | * zhihu:https://zhihu.com/people/lsxiao
14 | */
15 |
16 | class SchedulerProvider private constructor(private val main: Scheduler) {
17 | private val inout = Schedulers.io()
18 | private val computation = Schedulers.computation()
19 | private val trampoline = Schedulers.trampoline()
20 | private val single = Schedulers.single()
21 | private val new = Schedulers.newThread()
22 |
23 |
24 | enum class Tag {
25 | MAIN, IO, NEW, COMPUTATION, TRAMPOLINE, SINGLE
26 | }
27 |
28 | operator fun get(tag: SchedulerProvider.Tag): Scheduler = when (tag) {
29 | MAIN -> main
30 | IO -> inout
31 | COMPUTATION -> computation
32 | TRAMPOLINE -> trampoline
33 | SINGLE -> single
34 | NEW -> new
35 | }
36 |
37 | companion object {
38 |
39 | fun create(main: Scheduler?): SchedulerProvider {
40 | if (null == main) {
41 | throw NullPointerException("the scheduler main must be not null")
42 | }
43 |
44 | return SchedulerProvider(main)
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/entity/Event.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.entity;
2 |
3 | /**
4 | * write with Apollo
5 | * author:lsxiao
6 | * date:2017-05-24 10:36
7 | * github:https://github.com/lsxiao
8 | * zhihu:https://zhihu.com/people/lsxiao
9 | */
10 |
11 | public class Event {
12 | private String tag;
13 | private Object data;
14 | private int pid;
15 | private boolean isSticky = false;
16 |
17 | public Event() {
18 | }
19 |
20 | public Event(String tag, Object data, int pid) {
21 | this.tag = tag;
22 | this.data = data;
23 | this.pid = pid;
24 | }
25 |
26 | public Event(String tag, Object data, int pid, boolean isSticky) {
27 | this.tag = tag;
28 | this.data = data;
29 | this.pid = pid;
30 | this.isSticky = isSticky;
31 | }
32 |
33 | public String getTag() {
34 | return tag;
35 | }
36 |
37 | public void setTag(String tag) {
38 | this.tag = tag;
39 | }
40 |
41 | public Object getData() {
42 | return data;
43 | }
44 |
45 | public void setData(Object data) {
46 | this.data = data;
47 | }
48 |
49 | public int getPid() {
50 | return pid;
51 | }
52 |
53 | public void setPid(int pid) {
54 | this.pid = pid;
55 | }
56 |
57 | public boolean isSticky() {
58 | return isSticky;
59 | }
60 |
61 | public void setSticky(boolean sticky) {
62 | isSticky = sticky;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/ReceiveStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.Receive
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloDescriptor
8 | import com.lsxiao.apllo.processor.ApolloProcessor
9 | import java.util.*
10 | import javax.lang.model.element.Element
11 | import javax.lang.model.element.ExecutableElement
12 |
13 | /**
14 | * write with Apollo
15 | * author:lsxiao
16 | * date:2017-04-22 02:17
17 | * github:https://github.com/lsxiao
18 | * zhihu:https://zhihu.com/people/lsxiao
19 | */
20 |
21 | class ReceiveStep : BasicAnnotationProcessor.ProcessingStep {
22 | override fun annotations(): Set> = setOf(Receive::class.java)
23 |
24 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
25 | elementsByAnnotation.asMap().keys.forEach {
26 | elementsByAnnotation.asMap()[it]?.forEach { element ->
27 | val descriptor = ApolloDescriptor.newInstance(element as ExecutableElement)
28 | descriptor.tags = Arrays.asList(*MoreElements.asExecutable(element).getAnnotation(Receive::class.java).value)
29 | ApolloProcessor.sDescriptorMap.put(element, descriptor)
30 | }
31 | }
32 | return HashSet()
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | def config = parent.ext
5 |
6 | compileSdkVersion config.compileSdkVersion
7 | buildToolsVersion config.buildToolsVersion
8 |
9 | defaultConfig {
10 | applicationId "com.lsxiao.apollo.demo"
11 | minSdkVersion config.minSdkVersion
12 | targetSdkVersion config.targetSdkVersion
13 | versionCode 1
14 | versionName "1.0"
15 |
16 |
17 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
18 |
19 | }
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
31 | exclude group: 'com.android.support', module: 'support-annotations'
32 | })
33 | implementation 'com.android.support:appcompat-v7:27.0.2'
34 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
35 | testImplementation 'junit:junit:4.12'
36 |
37 | def libs = parent.ext.libs
38 | implementation libs.appcompat
39 | implementation libs.rxjava2
40 | implementation libs.rxandroid2
41 |
42 | implementation project(':core')
43 | implementation project(':ipc')
44 | annotationProcessor project(':processor')
45 | }
46 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/SubscribeStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.SubscribeOn
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloProcessor
8 | import java.util.*
9 | import javax.lang.model.element.Element
10 |
11 | /**
12 | * write with Apollo
13 | * author:lsxiao
14 | * date:2017-04-22 02:17
15 | * github:https://github.com/lsxiao
16 | * zhihu:https://zhihu.com/people/lsxiao
17 | */
18 |
19 | class SubscribeStep : BasicAnnotationProcessor.ProcessingStep {
20 | override fun annotations(): Set> = setOf(SubscribeOn::class.java)
21 |
22 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
23 | elementsByAnnotation.asMap().keys
24 | .map { elementsByAnnotation.asMap()[it] }
25 | .forEach { it ->
26 | it?.forEach list@ {
27 | val descriptor = ApolloProcessor.sDescriptorMap[it] ?: return@list
28 |
29 | if (MoreElements.isAnnotationPresent(it, SubscribeOn::class.java)) {
30 | descriptor.subscribeOn = MoreElements.asExecutable(it).getAnnotation(SubscribeOn::class.java).value
31 | }
32 | }
33 | }
34 | return HashSet()
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/base/BaseFragment.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.base;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.support.v4.app.Fragment;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | import com.lsxiao.apollo.core.Apollo;
11 | import com.lsxiao.apollo.core.contract.ApolloBinder;
12 |
13 | /**
14 | * author lsxiao
15 | * date 2016-08-23 19:15
16 | */
17 | public abstract class BaseFragment extends Fragment {
18 |
19 | public static final String TAG = BaseFragment.class.getSimpleName();
20 | protected View mRootView;
21 |
22 | private ApolloBinder mBinder;
23 |
24 | @Nullable
25 | @Override
26 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
27 | if (mRootView == null) {
28 | mRootView = inflater.inflate(getLayoutId(), container, false);
29 | }
30 | return mRootView;
31 | }
32 |
33 | @Override
34 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
35 | super.onViewCreated(view, savedInstanceState);
36 | mBinder = Apollo.bind(this);
37 | afterCreate(savedInstanceState);
38 | }
39 |
40 | @Override
41 | public void onDestroyView() {
42 | super.onDestroyView();
43 | if (null != mBinder) {
44 | mBinder.unbind();
45 | }
46 | }
47 |
48 | protected abstract int getLayoutId();
49 |
50 | protected abstract void afterCreate(Bundle savedInstanceState);
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/serialize/KryoSerializer.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core.serialize
2 |
3 | import com.esotericsoftware.kryo.Kryo
4 | import com.esotericsoftware.kryo.KryoException
5 | import com.esotericsoftware.kryo.io.Input
6 | import com.esotericsoftware.kryo.io.Output
7 | import java.io.ByteArrayInputStream
8 | import java.io.ByteArrayOutputStream
9 | import java.io.IOException
10 |
11 | /**
12 | * write with Apollo
13 | * author:lsxiao
14 | * date:2017-05-17 17:25
15 | * github:https://github.com/lsxiao
16 | * zhihu:https://zhihu.com/people/lsxiao
17 | */
18 |
19 | class KryoSerializer : Serializable {
20 | private val mKryo = Kryo()
21 |
22 | init {
23 | mKryo.references = false
24 | }
25 |
26 | override fun serialize(obj: Any): ByteArray {
27 | val outputStream = ByteArrayOutputStream()
28 | val output = Output(outputStream)
29 | mKryo.writeObject(output, obj)
30 | output.flush()
31 | output.close()
32 |
33 | val b = outputStream.toByteArray()
34 | try {
35 | outputStream.flush()
36 | outputStream.close()
37 | } catch (e: IOException) {
38 | e.printStackTrace()
39 | }
40 |
41 | return b
42 | }
43 |
44 | override fun deserialize(data: ByteArray, clazz: Class): T {
45 | val byteArrayInputStream = ByteArrayInputStream(data)
46 | val input = Input(byteArrayInputStream)
47 | val t = mKryo.readObject(input, clazz)
48 | try {
49 | input.close()
50 | } catch (e: KryoException) {
51 | e.printStackTrace()
52 | }
53 |
54 | return t
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/unittest/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | android {
5 | compileSdkVersion 26
6 |
7 |
8 |
9 | defaultConfig {
10 | applicationId "com.lsxiao.apollo.unittest"
11 | minSdkVersion 14
12 | targetSdkVersion 26
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 |
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 |
27 | }
28 |
29 | dependencies {
30 | implementation fileTree(dir: 'libs', include: ['*.jar'])
31 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
32 | implementation 'com.android.support:appcompat-v7:26.1.0'
33 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
34 |
35 | def libs = parent.ext.libs
36 | androidTestImplementation 'org.mockito:mockito-core:2.2.29'
37 | androidTestImplementation 'com.linkedin.dexmaker:dexmaker:2.2.0'
38 | androidTestImplementation 'com.linkedin.dexmaker:dexmaker-mockito:2.2.0'
39 | androidTestImplementation 'junit:junit:4.12'
40 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
41 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
42 | androidTestImplementation libs.rxjava2
43 | androidTestImplementation libs.rxandroid2
44 | androidTestImplementation project(':core')
45 | androidTestImplementation project(':ipc')
46 | androidTestAnnotationProcessor project(':processor')
47 | }
48 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/fragment/SubscriberDialogFragment.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.fragment;
2 |
3 | import android.os.Bundle;
4 | import android.widget.TextView;
5 |
6 | import com.lsxiao.apollo.core.annotations.Backpressure;
7 | import com.lsxiao.apollo.core.annotations.Receive;
8 | import com.lsxiao.apollo.core.annotations.Sticky;
9 | import com.lsxiao.apollo.demo.R;
10 | import com.lsxiao.apollo.demo.base.BaseDialogFragment;
11 |
12 | import io.reactivex.BackpressureStrategy;
13 |
14 | /**
15 | * author lsxiao
16 | * date 2016-08-23 21:01
17 | */
18 | public class SubscriberDialogFragment extends BaseDialogFragment {
19 | public static final String TAG = "SubscriberDialogFragment";
20 | private TextView mTvSentStickyEvent;
21 |
22 | public static SubscriberDialogFragment newInstance() {
23 |
24 | Bundle args = new Bundle();
25 |
26 | SubscriberDialogFragment fragment = new SubscriberDialogFragment();
27 | fragment.setArguments(args);
28 | return fragment;
29 | }
30 |
31 | @Override
32 | protected int getLayoutId() {
33 | return R.layout.dialog_subscriber;
34 | }
35 |
36 | @Sticky
37 | @Receive("sticky")
38 | public void onReceiveStickyEvent(String event) {
39 | mTvSentStickyEvent.setText(mTvSentStickyEvent.getText().toString() + event + ",");
40 | }
41 |
42 | @Override
43 | protected void afterCreate(Bundle savedInstanceState) {
44 | mTvSentStickyEvent = (TextView) mRootView.findViewById(R.id.tv_sent_sticky_event);
45 | }
46 |
47 | @Backpressure(BackpressureStrategy.DROP)
48 | @Receive("event")
49 | public void onReceiveEvent(String event) {
50 | mTvSentStickyEvent.setText(mTvSentStickyEvent.getText().toString() + event + ",");
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/step/BackpressureStep.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor.step
2 |
3 | import com.lsxiao.apollo.core.annotations.Backpressure
4 | import com.google.auto.common.BasicAnnotationProcessor
5 | import com.google.auto.common.MoreElements
6 | import com.google.common.collect.SetMultimap
7 | import com.lsxiao.apllo.processor.ApolloProcessor
8 | import io.reactivex.BackpressureStrategy
9 | import java.util.*
10 | import javax.lang.model.element.Element
11 |
12 | /**
13 | * write with Apollo
14 | * author:lsxiao
15 | * date:2017-04-22 02:17
16 | * github:https://github.com/lsxiao
17 | * zhihu:https://zhihu.com/people/lsxiao
18 | */
19 |
20 | class BackpressureStep : BasicAnnotationProcessor.ProcessingStep {
21 | override fun annotations(): Set> = setOf(Backpressure::class.java)
22 |
23 | override fun process(elementsByAnnotation: SetMultimap, Element>): Set {
24 | elementsByAnnotation.asMap().keys.forEach { clazz ->
25 | elementsByAnnotation.asMap()[clazz]?.forEach list@ { element ->
26 | val descriptor = ApolloProcessor.sDescriptorMap[element] ?: return@list
27 |
28 | if (MoreElements.isAnnotationPresent(element, Backpressure::class.java)) {
29 | MoreElements.asExecutable(element).getAnnotation(Backpressure::class.java).value.takeIf {
30 | it == BackpressureStrategy.BUFFER || it == BackpressureStrategy.DROP || it == BackpressureStrategy.LATEST
31 | }.let {
32 | if (it != null) {
33 | descriptor.backpressureStrategy = it
34 | }
35 | }
36 | }
37 | }
38 | }
39 | return HashSet()
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/config/dependencies.gradle:
--------------------------------------------------------------------------------
1 | allprojects {
2 | repositories {
3 | jcenter()
4 | google()
5 | mavenCentral()
6 | maven { url "https://www.jitpack.io" }
7 | maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
8 | }
9 | }
10 |
11 | ext {
12 | //Official
13 | buildToolsVersion = "27.0.2"
14 | compileSdkVersion = 27
15 | minSdkVersion = 14
16 | targetSdkVersion = 14
17 | support = "27.0.2"
18 |
19 | //libs
20 | rxjava2 = "2.1.7"
21 | rxandroid2 = "2.0.1"
22 |
23 | javapoet = "1.8.0"
24 | autoService = "1.0-rc4"
25 | autoCommon = "0.9"
26 | kotlin = "1.2.21"
27 | kryo = "4.0.0"//json parser
28 |
29 | libs = [
30 | supportV4 : "com.android.support:support-v4:$support",
31 | appcompat : "com.android.support:appcompat-v7:$support",
32 | recyclerView : "com.android.support:recyclerview-v7:$support",
33 | cardView : "com.android.support:cardview-v7:$support",
34 | supportDesign : "com.android.support:design:$support",
35 | supportAnnotation: "com.android.support:support-annotations:$support",
36 | rxjava2 : "io.reactivex.rxjava2:rxjava:$rxjava2",
37 | rxandroid2 : "io.reactivex.rxjava2:rxandroid:$rxandroid2",
38 | javapoet : "com.squareup:javapoet:$javapoet",
39 | autoService : "com.google.auto.service:auto-service:$autoService",
40 | autoCommon : "com.google.auto:auto-common:$autoCommon",
41 | kotlin : "org.jetbrains.kotlin:kotlin-stdlib:$kotlin",
42 | kryo : "com.esotericsoftware:kryo-shaded:$kryo"
43 | ]
44 |
45 |
46 | junit = "4.12"
47 |
48 | test = [
49 | junit: "junit:junit:$junit"
50 | ]
51 | }
--------------------------------------------------------------------------------
/demo/src/main/res/layout/fragment_subscriber.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
16 |
17 |
23 |
24 |
31 |
32 |
33 |
39 |
40 |
47 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/base/BaseDialogFragment.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.base;
2 |
3 | import android.app.Dialog;
4 | import android.os.Bundle;
5 | import android.support.annotation.NonNull;
6 | import android.support.annotation.Nullable;
7 | import android.support.v4.app.DialogFragment;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.view.Window;
12 |
13 | import com.lsxiao.apollo.core.Apollo;
14 | import com.lsxiao.apollo.core.contract.ApolloBinder;
15 |
16 | /**
17 | * author lsxiao
18 | * date 2016-08-23 19:15
19 | */
20 | public abstract class BaseDialogFragment extends DialogFragment {
21 |
22 | public static final String TAG = BaseDialogFragment.class.getSimpleName();
23 | protected View mRootView;
24 |
25 | private ApolloBinder mBinder;
26 |
27 | @NonNull
28 | @Override
29 | public Dialog onCreateDialog(Bundle savedInstanceState) {
30 | final Dialog dialog = new Dialog(getActivity());
31 | dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
32 | return dialog;
33 | }
34 |
35 | @Nullable
36 | @Override
37 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
38 | if (mRootView == null) {
39 | mRootView = inflater.inflate(getLayoutId(), container, false);
40 | }
41 | return mRootView;
42 | }
43 |
44 | @Override
45 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
46 | super.onViewCreated(view, savedInstanceState);
47 | mBinder = Apollo.bind(this);
48 | afterCreate(savedInstanceState);
49 | }
50 |
51 | @Override
52 | public void onDestroyView() {
53 | super.onDestroyView();
54 | if (null != mBinder) {
55 | mBinder.unbind();
56 | }
57 | }
58 |
59 | protected abstract int getLayoutId();
60 |
61 | protected abstract void afterCreate(Bundle savedInstanceState);
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/ApolloProcessor.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | import javax.annotation.processing.Processor;
8 | import javax.annotation.processing.RoundEnvironment;
9 | import javax.lang.model.SourceVersion;
10 | import javax.lang.model.element.Element;
11 |
12 | import com.google.auto.common.BasicAnnotationProcessor;
13 | import com.google.auto.service.AutoService;
14 | import com.google.common.collect.ImmutableSet;
15 | import com.lsxiao.apllo.processor.step.BackpressureStep;
16 | import com.lsxiao.apllo.processor.step.ObserveStep;
17 | import com.lsxiao.apllo.processor.step.ReceiveStep;
18 | import com.lsxiao.apllo.processor.step.StickyStep;
19 | import com.lsxiao.apllo.processor.step.SubscribeStep;
20 | import com.lsxiao.apllo.processor.step.TakeStep;
21 |
22 | @AutoService(Processor.class)
23 | public class ApolloProcessor extends BasicAnnotationProcessor {
24 | public static Map sDescriptorMap = new HashMap<>();
25 | private boolean mGenerated = false;
26 |
27 | @Override
28 | protected Iterable extends ProcessingStep> initSteps() {
29 | return ImmutableSet.of(
30 | new ReceiveStep(),
31 | new TakeStep(),
32 | new StickyStep(),
33 | new BackpressureStep(),
34 | new SubscribeStep(),
35 | new ObserveStep()
36 | );
37 | }
38 |
39 | @Override
40 | protected void postRound(RoundEnvironment roundEnv) {
41 | super.postRound(roundEnv);
42 | if (mGenerated || sDescriptorMap.isEmpty()) {
43 | return;
44 | }
45 | CodeGenerator.Companion.create(new ArrayList<>(sDescriptorMap.values()), processingEnv.getFiler()).generate();
46 | mGenerated = true;
47 | }
48 |
49 | @Override
50 | public SourceVersion getSupportedSourceVersion() {
51 | return SourceVersion.latestSupported();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/unittest/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/TestActivity.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo;
2 |
3 | import com.lsxiao.apollo.core.annotations.Receive;
4 | import com.lsxiao.apollo.demo.base.BaseActivity;
5 | import com.lsxiao.apollo.demo.fragment.ProducerFragment;
6 | import com.lsxiao.apollo.demo.fragment.SubscriberFragment;
7 | import com.lsxiao.apollo.demo.model.User;
8 |
9 | import android.content.Intent;
10 | import android.os.Bundle;
11 | import android.os.Process;
12 | import android.support.v4.app.Fragment;
13 | import android.util.Log;
14 | import android.view.View;
15 | import android.widget.TextView;
16 | import android.widget.Toast;
17 |
18 | public class TestActivity extends BaseActivity {
19 | public static final String TAG = TestActivity.class.getSimpleName();
20 |
21 | public String mLastEventMessage;
22 |
23 | @Override
24 | protected int getLayoutId() {
25 | return R.layout.activity_main;
26 | }
27 |
28 | @Override
29 | protected void afterCreate(Bundle savedInstanceState) {
30 | final Fragment subscriberFragment = SubscriberFragment.newInstance();
31 | final Fragment producerFragment = ProducerFragment.newInstance();
32 |
33 | getSupportFragmentManager()
34 | .beginTransaction()
35 | .replace(R.id.fl_subscriber, subscriberFragment, SubscriberFragment.TAG)
36 | .commit();
37 |
38 | getSupportFragmentManager()
39 | .beginTransaction()
40 | .replace(R.id.fl_producer, producerFragment, SubscriberFragment.TAG)
41 | .commit();
42 | ((TextView) findViewById(R.id.btn_start_service))
43 | .setText(String.format("Start TestService(cur pid=%s)", Process.myPid()));
44 | findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
45 | @Override
46 | public void onClick(View v) {
47 | Intent intent = new Intent(TestActivity.this, TestService.class);
48 | startService(intent);
49 | }
50 | });
51 |
52 | }
53 |
54 | @Receive("ipc")
55 | public void onIPCEvent(User user) {
56 | Toast.makeText(this, user.toString(), Toast.LENGTH_LONG).show();
57 | Log.d(TAG, "onIPCEvent: " + user);
58 | }
59 |
60 | @Receive("testRegisterAndEmit")
61 | public void testRegisterAndEmit(String message) {
62 | mLastEventMessage = message;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/fragment/SubscriberFragment.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.fragment;
2 |
3 | import android.os.Bundle;
4 | import android.widget.TextView;
5 |
6 | import com.lsxiao.apollo.core.annotations.Receive;
7 | import com.lsxiao.apollo.demo.R;
8 | import com.lsxiao.apollo.demo.base.BaseFragment;
9 | import com.lsxiao.apollo.demo.constant.Event;
10 | import com.lsxiao.apollo.demo.model.User;
11 |
12 | /**
13 | * author lsxiao
14 | * date 2016-08-23 19:14
15 | */
16 | public class SubscriberFragment extends BaseFragment {
17 | public static final String TAG = "SubscriberFragment";
18 | private TextView mTvReceiveEvent;
19 | private TextView mTvReceiveStickyEvent;
20 |
21 | public static SubscriberFragment newInstance() {
22 | Bundle args = new Bundle();
23 | SubscriberFragment fragment = new SubscriberFragment();
24 | fragment.setArguments(args);
25 | return fragment;
26 | }
27 |
28 | @Override
29 | protected int getLayoutId() {
30 | return R.layout.fragment_subscriber;
31 | }
32 |
33 | @Override
34 | protected void afterCreate(Bundle savedInstanceState) {
35 | mTvReceiveEvent = (TextView) mRootView.findViewById(R.id.tv_received_event);
36 | mTvReceiveStickyEvent = (TextView) mRootView.findViewById(R.id.tv_received_sticky_event);
37 | }
38 |
39 | @Receive(Event.DOBLUE_NUMBER)
40 | public void onEvent(double value) {
41 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
42 | }
43 |
44 | @Receive(Event.FLOAT_NUMBER)
45 | public void onEvent(float value) {
46 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
47 | }
48 |
49 | @Receive(Event.INT_NUMBER)
50 | public void onEvent(int value) {
51 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
52 | }
53 |
54 | @Receive(Event.OBJECT)
55 | public void onEvent() {
56 | }
57 |
58 |
59 | @Receive(Event.OBJECT)
60 | public void onEvent(User value) {
61 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
62 | }
63 |
64 |
65 | @Receive(Event.BOOL)
66 | public void onEvent(boolean value) {
67 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
68 | }
69 |
70 | @Receive(Event.STR)
71 | public void onEvent(String value) {
72 | mTvReceiveEvent.setText(mTvReceiveEvent.getText().toString() + value + ",");
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/lsxiao/apollo/demo/fragment/ProducerFragment.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.demo.fragment;
2 |
3 | import android.os.Bundle;
4 | import android.view.View;
5 | import android.widget.TextView;
6 |
7 | import com.lsxiao.apollo.core.Apollo;
8 | import com.lsxiao.apollo.demo.R;
9 | import com.lsxiao.apollo.demo.base.BaseFragment;
10 | import com.lsxiao.apollo.demo.constant.Event;
11 | import com.lsxiao.apollo.demo.model.User;
12 |
13 | /**
14 | * author lsxiao
15 | * date 2016-08-23 19:29
16 | */
17 | public class ProducerFragment extends BaseFragment implements View.OnClickListener {
18 | public static final String TAG = "ProducerFragment";
19 | private TextView mTvSentEvent;
20 | private TextView mTvSentStickyEvent;
21 | private SubscriberDialogFragment mSubscriberDialogFragment;
22 |
23 | public static ProducerFragment newInstance() {
24 | Bundle args = new Bundle();
25 | ProducerFragment fragment = new ProducerFragment();
26 | fragment.setArguments(args);
27 | return fragment;
28 | }
29 |
30 | @Override
31 | protected int getLayoutId() {
32 | return R.layout.fragment_producer;
33 | }
34 |
35 | @Override
36 | protected void afterCreate(Bundle savedInstanceState) {
37 | mRootView.findViewById(R.id.btn_send_event).setOnClickListener(this);
38 | mRootView.findViewById(R.id.btn_send_sticky_event).setOnClickListener(this);
39 | mRootView.findViewById(R.id.btn_show_dialog).setOnClickListener(this);
40 | mTvSentEvent = (TextView) mRootView.findViewById(R.id.tv_sent_event);
41 | mTvSentStickyEvent = (TextView) mRootView.findViewById(R.id.tv_sent_sticky_event);
42 | mSubscriberDialogFragment = SubscriberDialogFragment.newInstance();
43 | }
44 |
45 | @Override
46 | public void onClick(View view) {
47 | switch (view.getId()) {
48 | case R.id.btn_send_event: {
49 | Apollo.emit(Event.OBJECT, new User("lsxiao"));
50 | mTvSentEvent.setText(String.format("%sevent,", mTvSentEvent.getText().toString()));
51 | break;
52 | }
53 | case R.id.btn_send_sticky_event: {
54 | Apollo.emit("sticky", "sticky", true);
55 | mTvSentStickyEvent.setText(String.format("%ssticky,", mTvSentStickyEvent.getText().toString()));
56 | break;
57 | }
58 | case R.id.btn_show_dialog: {
59 | if (!mSubscriberDialogFragment.isAdded()) {
60 | mSubscriberDialogFragment = SubscriberDialogFragment.newInstance();
61 | }
62 | mSubscriberDialogFragment.show(getChildFragmentManager(), SubscriberDialogFragment.TAG);
63 | break;
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/demo/src/main/res/layout/fragment_producer.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
16 |
17 |
23 |
24 |
31 |
32 |
38 |
39 |
46 |
47 |
48 |
54 |
55 |
61 |
62 |
68 |
69 |
70 |
75 |
--------------------------------------------------------------------------------
/core/src/test/java/com/lsxiao/apollo/core/KryoSerializeTest.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core;
2 |
3 | import com.lsxiao.apollo.core.entity.Event;
4 | import com.lsxiao.apollo.core.serialize.KryoSerializer;
5 | import com.lsxiao.apollo.core.serialize.Serializable;
6 |
7 | import junit.framework.TestCase;
8 |
9 | import org.junit.Before;
10 | import org.junit.Test;
11 |
12 |
13 | /**
14 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
15 | */
16 | public class KryoSerializeTest extends TestCase {
17 | private Serializable mKryo;
18 | private TestClass mTestClass;
19 | private Event mEvent;
20 |
21 | private static class TestClass {
22 | private String testString;
23 | private int testInt;
24 | private float testFloat;
25 | private double testDouble;
26 | private boolean testBool;
27 |
28 | public TestClass() {
29 |
30 | }
31 |
32 | public TestClass(String testString, int testInt, float testFloat, double testDouble, boolean testBool) {
33 | this.testString = testString;
34 | this.testInt = testInt;
35 | this.testFloat = testFloat;
36 | this.testDouble = testDouble;
37 | this.testBool = testBool;
38 | }
39 |
40 | @Override
41 | public boolean equals(Object obj) {
42 | if (!(obj instanceof TestClass)) {
43 | return false;
44 | }
45 | TestClass toEqual = (TestClass) obj;
46 | return (toEqual.testBool == testBool) &&
47 | (toEqual.testDouble == testDouble) &&
48 | (toEqual.testFloat == testFloat) &&
49 | (toEqual.testInt == testInt) &&
50 | (toEqual.testString.equals(testString));
51 | }
52 |
53 | @Override
54 | public String toString() {
55 | return "TestClass{" +
56 | "testString='" + testString + '\'' +
57 | ", testInt=" + testInt +
58 | ", testFloat=" + testFloat +
59 | ", testDouble=" + testDouble +
60 | ", testBool=" + testBool +
61 | '}';
62 | }
63 | }
64 |
65 | @Before
66 | public void setUp() throws Exception {
67 | mTestClass = new TestClass("test", 1, 1f, 1d, true);
68 | mEvent = new Event("tag", mTestClass, 1, true);
69 | mKryo = new KryoSerializer();
70 | }
71 |
72 | @Test
73 | public void testTestClass() throws Exception {
74 | TestClass newTestClass = mKryo.deserialize(mKryo.serialize(mTestClass), TestClass.class);
75 | assertTrue(newTestClass.equals(mTestClass));
76 | }
77 |
78 | @Test
79 | public void testEvent() throws Exception {
80 | Event newEvent = mKryo.deserialize(mKryo.serialize(mEvent), Event.class);
81 | assertNotNull(newEvent);
82 | assertEquals(mEvent.getData(), newEvent.getData());
83 | assertEquals(mEvent.getPid(), newEvent.getPid());
84 | assertEquals(mEvent.getTag(), newEvent.getTag());
85 | }
86 |
87 | }
--------------------------------------------------------------------------------
/unittest/src/androidTest/java/com/lsxiao/apollo/unittest/BasicTest.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.unittest;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import com.lsxiao.apollo.core.Apollo;
8 | import com.lsxiao.apollo.core.annotations.Receive;
9 | import com.lsxiao.apollo.core.contract.ApolloBinder;
10 | import com.lsxiao.apollo.core.entity.SchedulerProvider;
11 | import com.lsxiao.apollo.core.serialize.KryoSerializer;
12 |
13 | import org.junit.After;
14 | import org.junit.Before;
15 | import org.junit.Test;
16 | import org.junit.runner.RunWith;
17 |
18 | import io.reactivex.android.schedulers.AndroidSchedulers;
19 | import io.reactivex.schedulers.Schedulers;
20 |
21 | import static junit.framework.Assert.assertEquals;
22 | import static junit.framework.Assert.assertFalse;
23 | import static junit.framework.Assert.assertNotNull;
24 | import static junit.framework.Assert.assertNull;
25 | import static junit.framework.Assert.assertTrue;
26 |
27 | /**
28 | * Instrumentation test, which will execute on an Android device.
29 | *
30 | * @see Testing documentation
31 | */
32 | @RunWith(AndroidJUnit4.class)
33 | public class BasicTest {
34 | private static final String TAG = "EVENT_TAG";
35 | private Context mContext;
36 |
37 | @Before
38 | public void setUp() throws Exception {
39 | mContext = InstrumentationRegistry.getTargetContext();
40 | Apollo.init(AndroidSchedulers.mainThread(), mContext);
41 | }
42 |
43 | @Test
44 | public void testContext() {
45 | assertEquals(Apollo.getContext(), mContext);
46 | }
47 |
48 | @Test
49 | public void testSchedulerProvider() {
50 | assertEquals(Apollo.getSchedulerProvider().get(SchedulerProvider.Tag.MAIN), AndroidSchedulers.mainThread());
51 | assertEquals(Apollo.getSchedulerProvider().get(SchedulerProvider.Tag.IO), Schedulers.io());
52 | assertEquals(Apollo.getSchedulerProvider().get(SchedulerProvider.Tag.COMPUTATION), Schedulers.computation());
53 | assertEquals(Apollo.getSchedulerProvider().get(SchedulerProvider.Tag.SINGLE), Schedulers.single());
54 | assertEquals(Apollo.getSchedulerProvider().get(SchedulerProvider.Tag.TRAMPOLINE), Schedulers.trampoline());
55 | }
56 |
57 | @Test
58 | public void testSticky() {
59 | String msg = "msg";
60 | String tag = "tag";
61 | Apollo.emit(tag, msg, true);
62 | assertEquals(Apollo.getStickyEvent(tag), msg);
63 |
64 | Apollo.removeStickyEvent(tag);
65 | assertNull(Apollo.getStickyEvent(tag));
66 |
67 | Apollo.emit(tag, msg, true);
68 | assertEquals(Apollo.getStickyEvent(tag), msg);
69 |
70 | Apollo.removeAllStickyEvent();
71 | assertNull(Apollo.getStickyEvent(tag));
72 | }
73 |
74 | @Test
75 | public void testBindUnBind() throws Exception {
76 | ApolloBinder binder = Apollo.bind(this);
77 | assertTrue(Apollo.isBind(this));
78 | binder.unbind();
79 | assertFalse(Apollo.isBind(this));
80 | }
81 |
82 | @Test
83 | public void testSerializer() {
84 | assertNotNull(Apollo.getSerializer());
85 | assertTrue(Apollo.getSerializer() instanceof KryoSerializer);
86 | }
87 |
88 | @Receive(TAG)
89 | public void test(String message) {
90 | System.out.println(message);
91 | }
92 |
93 | @After
94 | public void tearDown() throws Exception {
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/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 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/README-EN.md:
--------------------------------------------------------------------------------
1 | # Apollo [](https://jitpack.io/#lsxiao/Apollo)
2 |
3 |
4 |
5 | Inter-Process Communication , Compile-time Annotation.
6 |
7 | Apollo , make RxBus simplified but not simple.
8 |
9 | [English Document](https://github.com/lsxiao/Apollo/blob/master/README-EN.md)
10 |
11 | ## Start
12 |
13 | quick integration with 3 minutes
14 |
15 | ### integration
16 |
17 | use jitpack in your module.
18 | ```groovy
19 | allProjects {
20 | repositories {
21 | maven { url "https://www.jitpack.io" }
22 | }
23 | }
24 | ```
25 |
26 | depend these in your build.gralde.
27 |
28 | ```groovy
29 | dependencies {
30 | implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
31 |
32 | implementation "com.github.lsxiao.Apollo:core:1.0.2"
33 |
34 | //IPC module,optional
35 | implementation "com.github.lsxiao.Apollo:ipc:1.0.2"
36 |
37 | annotationProcessor "com.github.lsxiao.Apollo:processor:1.0.2"
38 |
39 | //for kotlin
40 | kapt "com.github.lsxiao.Apollo:processor:1.0.2"
41 | }
42 | ```
43 |
44 | ## Usage
45 |
46 | ### init
47 |
48 | `ApolloBinderGeneratorImpl`在编译时生成。
49 |
50 | ```java
51 | Apollo.init(AndroidSchedulers.mainThread(), this);
52 | ```
53 |
54 | ### bind/unbind
55 |
56 | In order to avoid memory leaks, it should be bind and unbind within the component lifecycle.
57 | ```java
58 | public abstract class BaseActivity extends Activity {
59 | private ApolloBinder mBinder;
60 |
61 | @Override
62 | protected void onCreate(Bundle savedInstanceState) {
63 | ...
64 | mBinder = Apollo.bind(this);
65 | }
66 |
67 | @Override
68 | protected void onDestroy() {
69 | ...
70 | if(mBinder != null){
71 | mBinder.unbind();
72 | }
73 | }
74 | ...
75 | }
76 |
77 | ```
78 |
79 | ### emit
80 | make emit easier.
81 | ```java
82 | Apollo.emit("event","hello apollo")
83 | ```
84 |
85 | ### receive
86 | receive anywhere you like.
87 | ```java
88 | @Receive("event")
89 | public void onEvent(String message){
90 | ...
91 | }
92 | ```
93 | ### ipc
94 | default is closed.
95 | ```
96 | Apollo.init(AndroidSchedulers.mainThread(), this,true);
97 | ```
98 |
99 | your data object which need to ipc must has a non-parameter-constructor,because apollo used kory to serialize object.
100 |
101 | more usage see below.
102 |
103 | ## Advanced Usage
104 | ### Annotation List
105 | **Notice!!!**,The annotated function must be public, and @Receive is required ,others is optional.
106 |
107 | | annotation | parameter | description | default |
108 | |---------------|--------|-----------------------------------------------------------------------------------------------|----------------------------|
109 | | @Receive | | string tag list, or a string | |
110 | | @Sticky | remove | is remove after receive event. | ture |
111 | | @SubscribeOn | | subscribe on scheduler | SchedulerProvider.Tag.IO |
112 | | @ObserveOn | | observe on scheduler | SchedulerProvider.Tag.MAIN |
113 | | @Take | | how many times can be received. | |
114 | | @Backpressure | | backpressure strategy(BackpressureStrategy.BUFFER,BackpressureStrategy.DROP,BackpressureStrategy.LATEST) | |
115 |
116 | ### Method
117 |
118 | ```java
119 | boolean sticky = true;
120 |
121 | //only tag
122 | Apollo.emit("tag");
123 | //tag and object
124 | Apollo.emit("tag","event");
125 |
126 | //stikcy(can received event which is annotated by @Sticky)
127 | Apollo.emit("tag","event",stikcy)
128 | //only tag and stikcy
129 | Apollo.emit("tag",sticky)
130 | ```
131 |
132 | ### Custom Serializer
133 | Apollo use kory to serialize object,you can override it by providing a serializer.
134 | ```java
135 | Apollo.serializer(new Serializable() {
136 | @NotNull
137 | @Override
138 | public byte[] serialize(@NotNull Object obj) {
139 | ...
140 | }
141 |
142 | @Override
143 | public T deserialize(@NotNull byte[] data, @NotNull Class clazz) {
144 | ...
145 | }
146 | });
147 | ```
148 |
149 | ## ProGuard
150 | ```
151 | -dontwarn com.esotericsoftware.kryo.**
152 | -dontwarn org.objenesis.instantiator.**
153 | -dontwarn org.codehaus.**
154 | -dontwarn java.nio.**
155 | -dontwarn java.lang.invoke.**
156 | -keep class com.lsxiao.apollo.generate.** { *; }
157 | ```
158 |
159 | ## Build with ReactiveX
160 |
161 | * [RxJava2](https://github.com/ReactiveX/RxJava) - Reactive Extensions for the JVM
162 | * [RxAndroid2](https://github.com/ReactiveX/RxAndroid) - Reactive Extensions for Android
163 |
164 | ## How to contribute
165 |
166 | welcome pr.
167 |
168 | ## Versioning
169 | We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/lsxiao/Apollo/tags).
170 |
171 | ## Authors
172 |
173 | * **lsxiao** - *Android developer* - [lsxiao](https://github.com/lsxiao)
174 | See also the list of [contributors](https://github.com/lsxiao/Apollo/contributors) who participated in this project.
175 |
176 | ## License
177 |
178 | Apache License Version 2.0
179 |
180 | ## Acknowledgments
181 |
182 | * All I love, and who love me.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Apollo [](https://jitpack.io/#lsxiao/Apollo)
2 |
3 |
4 |
5 | > EventBus by RxJava
6 |
7 | - 基于RxJava
8 | - 基于编译时注解技术,编译时生成绑定代码,非反射,性能0损耗
9 | - 支持进程间通信
10 | - 支持@Tag注解,支持多重Tag
11 | - 支持@Sticky注解
12 | - 支持@Take注解,接收指定次数事件
13 | - 支持@SubscribeOn注解,指定订阅线程
14 | - 支持@ObserveOn注解,指定观察线程
15 | - 支持@Backpressure注解,支持3种背压策略(BackpressureStrategy.BUFFER,BackpressureStrategy.DROP,BackpressureStrategy.LATEST)
16 | - 支持apollo core 非注解式使用
17 |
18 | [English Document](https://github.com/lsxiao/Apollo/blob/master/README-EN.md)
19 |
20 |
21 | ## Todo
22 | - 重写demo
23 | - 完整的单元测试(已完成30%,见unittest module)
24 |
25 | ## 开始
26 |
27 | 用3分钟时间快速集成Apollo
28 |
29 | ### 集成
30 |
31 | 使用jitpack第三方依赖库
32 | ```groovy
33 | allProjects {
34 | repositories {
35 | maven { url "https://www.jitpack.io" }
36 | }
37 | }
38 | ```
39 |
40 | 在项目所在build.gralde添加依赖
41 |
42 | ```groovy
43 | dependencies {
44 | //Apollo依赖RxAndroid2,请使用最新的版本
45 | implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
46 |
47 | //Apollo的核心库
48 | implementation "com.github.lsxiao.Apollo:core:1.0.2"
49 |
50 | //IPC,如不需要可以不依赖
51 | implementation "com.github.lsxiao.Apollo:ipc:1.0.2"
52 |
53 | //Apollo的编译时注解处理器
54 | annotationProcessor "com.github.lsxiao.Apollo:processor:1.0.2"
55 |
56 | //如果你使用的是kotlin,请使用kapt
57 | kapt "com.github.lsxiao.Apollo:processor:1.0.2"
58 | }
59 | ```
60 |
61 | ## 使用
62 |
63 | ### 初始化
64 |
65 | `ApolloBinderGeneratorImpl`在编译时生成。
66 |
67 | ```java
68 | Apollo.init(AndroidSchedulers.mainThread(), this);
69 | ```
70 |
71 | ### 绑定/解绑
72 |
73 | 为了避免内存泄露,应在组件生命周期内绑定和解绑。
74 | ```java
75 | public abstract class BaseActivity extends Activity {
76 | private ApolloBinder mBinder;
77 |
78 | @Override
79 | protected void onCreate(Bundle savedInstanceState) {
80 | ...
81 | mBinder = Apollo.bind(this);
82 | }
83 |
84 | @Override
85 | protected void onDestroy() {
86 | ...
87 | if(mBinder != null){
88 | mBinder.unbind();
89 | }
90 | }
91 | ...
92 | }
93 |
94 | ```
95 |
96 | ### 发送
97 | 让发送更简单
98 | ```java
99 | Apollo.emit("event","hello apollo")
100 | ```
101 |
102 | ### 接收
103 | 让接收更自在
104 | ```java
105 | @Receive("event")
106 | public void onEvent(String message){
107 | ...
108 | }
109 | ```
110 |
111 | ### 进程间通信(IPC)
112 |
113 | 默认关闭
114 | ```
115 | Apollo.init(AndroidSchedulers.mainThread(), this,true);
116 | ```
117 |
118 | **!!!注意:**由于默认采用kryo序列化,所以任何需要在进程间传输的数据对象,自己包括其内部的成员对象都必须有一个默认的无参构造函数!!!
119 |
120 | ## 高级用法
121 | ### 注解
122 | **注意!!!**,被注解的函数一定得是public修饰,且@Receive是必须注解,其余为可选注解。
123 |
124 | | 注解 | 参数 | 描述 | 默认值 |
125 | |---------------|--------|-----------------------------------------------------------------------------------------------|----------------------------|
126 | | @Receive | | 接收一个字符串tag数组,或者单个字符串tag | 无 |
127 | | @Sticky | remove | 接收后是否清除stikcy事件 | ture |
128 | | @SubscribeOn | | 订阅所在线程 | SchedulerProvider.Tag.IO |
129 | | @ObserveOn | | 观察所在线程 | SchedulerProvider.Tag.MAIN |
130 | | @Take | | 接收多少次事件,int型参数 | 无 |
131 | | @Backpressure | | 背压策略(BackpressureStrategy.BUFFER,BackpressureStrategy.DROP,BackpressureStrategy.LATEST) | 无 |
132 |
133 | ### 更多方法
134 |
135 | ```java
136 | boolean sticky = true;
137 |
138 | //只有tag
139 | Apollo.emit("tag");
140 | //tag和数据实体
141 | Apollo.emit("tag","event");
142 |
143 | //stikcy(只有被@Sticky注解的函数才能收到sticky事件)
144 | Apollo.emit("tag","event",stikcy)
145 |
146 | //只有tag的stikcy调用
147 | Apollo.emit("tag",sticky)
148 | ```
149 | **注意**,在emit一个boolean变量的时候,**正确写法**:
150 |
151 | `Apollo.emit("tag",true,sticky)`
152 |
153 | **错误写法**,这样直接就发送了一个不带参数的sticky事件:
154 |
155 | ~~`Apollo.emit("tag",true)`~~
156 |
157 | ### 自定义Serializer
158 | Apollo默认采用kryo来序列化IPC数据对象,你可以提供一个Serializer来修改默认的实现。
159 | ```java
160 | Apollo.serializer(new Serializable() {
161 | @NotNull
162 | @Override
163 | public byte[] serialize(@NotNull Object obj) {
164 | ...
165 | }
166 |
167 | @Override
168 | public T deserialize(@NotNull byte[] data, @NotNull Class clazz) {
169 | ...
170 | }
171 | });
172 | ```
173 |
174 | ## 混淆
175 | ```
176 | -dontwarn com.esotericsoftware.kryo.**
177 | -dontwarn org.objenesis.instantiator.**
178 | -dontwarn org.codehaus.**
179 | -dontwarn java.nio.**
180 | -dontwarn java.lang.invoke.**
181 | -keep class com.lsxiao.apollo.generate.** { *; }
182 | ```
183 |
184 | ## 测试
185 | 全面而完善的测试是开源库质量的保证,目前测试用例正在不断完善中:)
186 |
187 | ### core module
188 | `KryoSerializeTest`
189 |
190 | ### unit test module
191 | `unittest`
192 |
193 | ## 构建于ReactiveX之上
194 |
195 | * [RxJava2](https://github.com/ReactiveX/RxJava) - Reactive Extensions for the JVM
196 | * [RxAndroid2](https://github.com/ReactiveX/RxAndroid) - Reactive Extensions for Android
197 |
198 | ## 版本
199 | 我们使用 [语义化版本控制规范](http://semver.org/) 作为版本管理,有关可用的版本,请参阅此 [标签列表](https://github.com/lsxiao/Apollo/tags)。
200 |
201 | ## 作者
202 |
203 | * **lsxiao** - [lsxiao](https://github.com/lsxiao)
204 |
205 | 更多 [贡献者](https://github.com/lsxiao/Apollo/contributors) 请参考这个项目的列表。
206 |
207 | ## 开源许可
208 |
209 | Apache License Version 2.0
210 |
--------------------------------------------------------------------------------
/unittest/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/unittest/src/androidTest/java/com/lsxiao/apollo/unittest/BusTest.java:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.unittest;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.annotation.UiThreadTest;
6 | import android.support.test.runner.AndroidJUnit4;
7 |
8 | import com.lsxiao.apollo.core.Apollo;
9 | import com.lsxiao.apollo.core.annotations.ObserveOn;
10 | import com.lsxiao.apollo.core.annotations.Receive;
11 | import com.lsxiao.apollo.core.annotations.Sticky;
12 | import com.lsxiao.apollo.core.annotations.SubscribeOn;
13 | import com.lsxiao.apollo.core.annotations.Take;
14 | import com.lsxiao.apollo.core.contract.ApolloBinder;
15 | import com.lsxiao.apollo.core.entity.SchedulerProvider;
16 |
17 | import org.junit.After;
18 | import org.junit.Before;
19 | import org.junit.Test;
20 | import org.junit.runner.RunWith;
21 | import org.mockito.Mockito;
22 |
23 | import io.reactivex.android.schedulers.AndroidSchedulers;
24 |
25 | import static org.mockito.Mockito.atMost;
26 | import static org.mockito.Mockito.times;
27 |
28 | /**
29 | * Instrumentation test, which will execute on an Android device.
30 | *
31 | * @see Testing documentation
32 | */
33 | @RunWith(AndroidJUnit4.class)
34 | public class BusTest {
35 | private static final String TAG = "EVENT_TAG";
36 | private ApolloBinder mApolloBinder;
37 | private Subscriber mSubscriber;
38 |
39 | @Before
40 | public void setUp() throws Exception {
41 | Context context = InstrumentationRegistry.getTargetContext();
42 | Apollo.init(AndroidSchedulers.mainThread(), context);
43 |
44 | //for sticky test,before subscriber create and bind.
45 | Apollo.emit("receiveSticky", "apollo", true);
46 |
47 | mSubscriber = Mockito.mock(Subscriber.class);
48 | mApolloBinder = Apollo.bind(mSubscriber);
49 | }
50 |
51 |
52 | @Test
53 | @UiThreadTest
54 | public void emitString() throws Exception {
55 | Apollo.emit(TAG, "apollo");
56 | Mockito.verify(mSubscriber).onString("apollo");
57 | }
58 |
59 | @Test
60 | @UiThreadTest
61 | public void emitInt() throws Exception {
62 | Apollo.emit(TAG, 1);
63 | Mockito.verify(mSubscriber).onInt(1);
64 | }
65 |
66 |
67 | @Test
68 | @UiThreadTest
69 | public void emitLong() throws Exception {
70 | Apollo.emit(TAG, 1L);
71 | Mockito.verify(mSubscriber).onLong(1L);
72 | }
73 |
74 | @Test
75 | @UiThreadTest
76 | public void emitBoolean() throws Exception {
77 | Apollo.emit(TAG, false, false);
78 | Mockito.verify(mSubscriber).onBoolean(false);
79 | }
80 |
81 |
82 | @Test
83 | @UiThreadTest
84 | public void emitChar() throws Exception {
85 | Apollo.emit(TAG, 'x');
86 | Mockito.verify(mSubscriber).onChar('x');
87 | }
88 |
89 |
90 | @Test
91 | @UiThreadTest
92 | public void receiveTimes() throws Exception {
93 | Apollo.emit("receiveTimes", "apollo");
94 | Mockito.verify(mSubscriber, times(1)).onTakeMultiTimes("apollo");
95 |
96 | Apollo.emit("receiveTimes", "apollo");
97 | Apollo.emit("receiveTimes", "apollo");
98 | Mockito.verify(mSubscriber, times(3)).onTakeMultiTimes("apollo");
99 |
100 | Apollo.emit("receiveTimes", "apollo");
101 | Apollo.emit("receiveTimes", "apollo");
102 | Mockito.verify(mSubscriber, atMost(4)).onTakeMultiTimes("apollo");
103 | }
104 |
105 |
106 | @Test
107 | @UiThreadTest
108 | public void receiveMultiTags() throws Exception {
109 | Apollo.emit("tag-1", "apollo");
110 | Mockito.verify(mSubscriber, times(1)).receiveMultiTags("apollo");
111 | Apollo.emit("tag-2", "apollo");
112 | Mockito.verify(mSubscriber, times(2)).receiveMultiTags("apollo");
113 | }
114 |
115 |
116 | @Test
117 | @UiThreadTest
118 | public void receiveNoParam() throws Exception {
119 | Apollo.emit("receiveNoParam");
120 | Mockito.verify(mSubscriber, times(1)).receiveNoParam();
121 | }
122 |
123 | @Test
124 | @UiThreadTest
125 | public void receiveSticky() throws Exception {
126 | Mockito.verify(mSubscriber, times(1)).receiveSticky("apollo");
127 | }
128 |
129 |
130 | public class Subscriber {
131 | @Receive("receiveSticky")
132 | @Sticky
133 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
134 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
135 | public void receiveSticky(String msg) {
136 |
137 | }
138 |
139 | @Receive("receiveNoParam")
140 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
141 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
142 | public void receiveNoParam() {
143 |
144 | }
145 |
146 | @Receive({"tag-1", "tag-2"})
147 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
148 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
149 | public void receiveMultiTags(String msg) {
150 |
151 | }
152 |
153 |
154 | @Receive("receiveTimes")
155 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
156 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
157 | @Take(4)
158 | public void onTakeMultiTimes(String msg) {
159 |
160 | }
161 |
162 | @Receive(TAG)
163 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
164 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
165 | public void onString(String msg) {
166 |
167 | }
168 |
169 | @Receive(TAG)
170 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
171 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
172 | public void onInt(int number) {
173 |
174 | }
175 |
176 | @Receive(TAG)
177 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
178 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
179 | public void onLong(long number) {
180 |
181 | }
182 |
183 | @Receive(TAG)
184 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
185 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
186 | public void onBoolean(boolean value) {
187 |
188 | }
189 |
190 | @Receive(TAG)
191 | @SubscribeOn(SchedulerProvider.Tag.TRAMPOLINE)
192 | @ObserveOn(SchedulerProvider.Tag.TRAMPOLINE)
193 | public void onChar(char value) {
194 |
195 | }
196 | }
197 |
198 | @After
199 | public void tearDown() throws Exception {
200 | mApolloBinder.unbind();
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/core/src/main/java/com/lsxiao/apollo/core/Apollo.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apollo.core
2 |
3 | import com.lsxiao.apollo.core.contract.ApolloBinder
4 | import com.lsxiao.apollo.core.contract.ApolloBinderGenerator
5 | import com.lsxiao.apollo.core.entity.ApolloBinderImpl
6 | import com.lsxiao.apollo.core.entity.Event
7 | import com.lsxiao.apollo.core.entity.SchedulerProvider
8 | import com.lsxiao.apollo.core.serialize.KryoSerializer
9 | import com.lsxiao.apollo.core.serialize.Serializable
10 | import io.reactivex.Flowable
11 | import io.reactivex.Scheduler
12 | import io.reactivex.processors.FlowableProcessor
13 | import io.reactivex.processors.PublishProcessor
14 | import kotlin.properties.Delegates
15 |
16 |
17 | /**
18 | * author lsxiao
19 | * date 2016-05-09 17:27
20 | */
21 | class Apollo private constructor() {
22 | private val mFlowableProcessor: FlowableProcessor by lazy {
23 | PublishProcessor.create().toSerialized()
24 | }
25 | //用于保存stick事件
26 | private val mStickyEventMap: MutableMap = HashMap()
27 | //用于保存SubscriptionBinder
28 | private val mBindTargetMap: MutableMap = HashMap()
29 | private var mApolloBinderGenerator: ApolloBinderGenerator by Delegates.notNull()
30 | private var mSchedulerProvider: SchedulerProvider by Delegates.notNull()
31 | private var mContext: Any by Delegates.notNull()
32 | private var mSerializer: Serializable = KryoSerializer()
33 | private var mIPCEnable = false
34 | private var mIsApolloBinderClassNotFound = false
35 | private var mIsIPCModuleClassNotFound = false
36 |
37 | companion object {
38 | private var sInstance: Apollo? = null
39 |
40 | /**
41 | * 返回一个Apollo的单例对象
42 |
43 | * @return Apollo
44 | */
45 | @JvmStatic
46 | @Synchronized
47 | private fun get(): Apollo {
48 | if (null == Apollo.Companion.sInstance) {
49 | Apollo.Companion.sInstance = Apollo()
50 | }
51 | return Apollo.Companion.sInstance as Apollo
52 | }
53 |
54 | @Deprecated(message = "this method is not support ipc", replaceWith = ReplaceWith("use init(AndroidSchedulers.mainThread(), ApolloBinderGeneratorImpl.instance(), getApplicationContext()) to instead"), level = DeprecationLevel.HIDDEN)
55 | @JvmStatic
56 | fun init(main: Scheduler, binder: ApolloBinderGenerator) {
57 | Apollo.Companion.init(main, binder, Any())
58 | }
59 |
60 | @Deprecated(message = "this method is not support ipc", replaceWith = ReplaceWith("use init(AndroidSchedulers.mainThread(), getApplicationContext()) to instead"), level = DeprecationLevel.WARNING)
61 | @JvmStatic
62 | fun init(main: Scheduler, binder: ApolloBinderGenerator, context: Any) {
63 | init(main, context)
64 | }
65 |
66 | @Deprecated(message = "this method is not support ipc", replaceWith = ReplaceWith("use init(AndroidSchedulers.mainThread(), getApplicationContext(),true) to instead"), level = DeprecationLevel.WARNING)
67 | @JvmStatic
68 | fun init(main: Scheduler, binder: ApolloBinderGenerator, context: Any, ipcEnable: Boolean = false) {
69 | init(main, context, ipcEnable)
70 | }
71 |
72 | @JvmStatic
73 | fun init(main: Scheduler, context: Any) {
74 | init(main, context, false)
75 | }
76 |
77 | @JvmStatic
78 | fun init(main: Scheduler, context: Any, ipcEnable: Boolean = false) {
79 | try {
80 | val generatorImplClass = Class.forName("com.lsxiao.apollo.generate.ApolloBinderGeneratorImpl") as Class
81 | val staticInstanceMethod = generatorImplClass.getMethod("instance")
82 | val generator = staticInstanceMethod.invoke(null) as ApolloBinderGenerator
83 |
84 | Apollo.get().mApolloBinderGenerator = generator
85 |
86 | } catch (e: ClassNotFoundException) {
87 | Apollo.get().mIsApolloBinderClassNotFound = true
88 | }
89 |
90 | Apollo.get().mSchedulerProvider = SchedulerProvider.Companion.create(main)
91 | Apollo.get().mContext = context
92 | Apollo.get().mIPCEnable = ipcEnable
93 |
94 | if (ipcEnable) {
95 | registerIPCReceiver(context)
96 | }
97 |
98 | }
99 |
100 | private fun registerIPCReceiver(context: Any) {
101 | try {
102 | val intentFilterClass = Class.forName("android.content.IntentFilter")
103 |
104 | val intentFilterConstructor = intentFilterClass.getConstructor(String::class.java)
105 |
106 | val broadcastReceiverClass = Class.forName("android.content.BroadcastReceiver")
107 |
108 | val ipcBroadcastReceiverClass = Class.forName("com.lsxiao.apollo.ipc.ApolloProcessEventReceiver")
109 |
110 | val registerBroadcastReceiverMethod = context.javaClass.getMethod("registerReceiver", broadcastReceiverClass, intentFilterClass)
111 |
112 | registerBroadcastReceiverMethod.invoke(context, ipcBroadcastReceiverClass.newInstance(), intentFilterConstructor.newInstance("apollo"))
113 | } catch (ignore: ClassNotFoundException) {
114 | Apollo.get().mIsIPCModuleClassNotFound = true
115 | }
116 | }
117 |
118 |
119 | @JvmStatic
120 | fun serializer(serializer: Serializable) {
121 | Apollo.get().mSerializer = serializer
122 | }
123 |
124 | @JvmStatic
125 | fun getSerializer() = Apollo.get().mSerializer
126 |
127 |
128 | /**
129 | * 判断是否有订阅者
130 | */
131 | @JvmStatic
132 | fun hasSubscribers(): Boolean {
133 | return Apollo.get().mFlowableProcessor.hasSubscribers()
134 | }
135 |
136 | /**
137 | * 绑定Activity或者Fragment
138 |
139 | * @param o Object
140 | * *
141 | * @return ApolloBinder
142 | */
143 | @JvmStatic
144 | fun bind(o: Any?): ApolloBinder {
145 | if (null == o) {
146 | throw java.lang.NullPointerException("object to subscribe must not be null")
147 | }
148 |
149 | return Apollo.Companion.uniqueBind(o)
150 | }
151 |
152 |
153 | /**
154 | * 绑定Activity或者Fragment
155 |
156 | * @param o Object
157 | * *
158 | * @return ApolloBinder
159 | */
160 | @JvmStatic
161 | fun isBind(o: Any?): Boolean {
162 | if (o == null) {
163 | return false
164 | }
165 | val uniqueId = System.identityHashCode(o)
166 | return Apollo.get().mBindTargetMap.containsKey(uniqueId)
167 | }
168 |
169 | /**
170 | * 唯一绑定,避免重复绑定到相同的对象
171 |
172 | * @param obj Object
173 | * *
174 | * @return ApolloBinder
175 | */
176 | @JvmStatic
177 | private fun uniqueBind(obj: Any): ApolloBinder {
178 | //找不到生成的绑定类
179 | if (Apollo.get().mIsApolloBinderClassNotFound) {
180 | return ApolloBinderImpl(obj)
181 | }
182 |
183 | val uniqueId = System.identityHashCode(obj)
184 |
185 | var binder: ApolloBinder
186 |
187 | //对象已有绑定记录
188 | if (Apollo.get().mBindTargetMap.containsKey(uniqueId)) {
189 | binder = Apollo.get().mBindTargetMap[uniqueId] as ApolloBinder
190 | //绑定已经解绑
191 | if (binder.isUnbind()) {
192 | //移除已经解绑的binder
193 | Apollo.get().mBindTargetMap.remove(uniqueId)
194 | //重新绑定
195 | binder = Apollo.get().mApolloBinderGenerator.generate(obj)
196 | //保存到map中
197 | Apollo.get().mBindTargetMap.put(uniqueId, binder)
198 | }
199 | } else {
200 | binder = Apollo.get().mApolloBinderGenerator.generate(obj)
201 | Apollo.get().mBindTargetMap.put(uniqueId, binder)
202 | }
203 | return binder
204 | }
205 |
206 | @JvmStatic
207 | internal fun unBind(o: Any) {
208 | val uniqueId = System.identityHashCode(o)
209 | Apollo.get().mBindTargetMap.remove(uniqueId)
210 | }
211 |
212 | @JvmStatic
213 | fun toFlowable(tag: String): Flowable {
214 | return Apollo.Companion.toFlowable(arrayOf(tag), Any::class.java)
215 | }
216 |
217 | @JvmStatic
218 | fun toFlowable(tags: Array): Flowable {
219 | return Apollo.Companion.toFlowable(tags, Any::class.java)
220 | }
221 |
222 | @JvmStatic
223 | fun toFlowable(tags: Array?, eventType: Class?): Flowable {
224 | if (null == eventType) {
225 | throw java.lang.NullPointerException("the eventType must be not null")
226 | }
227 |
228 | if (null == tags) {
229 | throw java.lang.NullPointerException("the tags must be not null")
230 | }
231 |
232 | if (tags.isEmpty()) {
233 | throw java.lang.IllegalArgumentException("the tags must be not empty")
234 | }
235 |
236 | return Apollo.get().mFlowableProcessor
237 | .filter { event ->
238 | java.util.Arrays.asList(*tags).contains(event.tag) && eventType.isInstance(event.data)
239 | }
240 | .flatMap { event -> Flowable.just(eventType.cast(event.data)) }
241 | }
242 |
243 | @JvmStatic
244 | fun toFlowableSticky(tag: String): Flowable {
245 | return Apollo.Companion.toFlowableSticky(arrayOf(tag))
246 | }
247 |
248 | @JvmStatic
249 | fun toFlowableSticky(tags: Array): Flowable {
250 | return Apollo.Companion.toFlowableSticky(tags, Any::class.java)
251 | }
252 |
253 | @JvmStatic
254 | fun toFlowableSticky(tags: Array?, eventType: Class?): Flowable {
255 | if (null == eventType) {
256 | throw java.lang.NullPointerException("the eventType must be not null")
257 | }
258 |
259 | if (null == tags) {
260 | throw java.lang.NullPointerException("the tags must be not null")
261 | }
262 |
263 | if (tags.isEmpty()) {
264 | throw java.lang.IllegalArgumentException("the tags must be not empty")
265 | }
266 |
267 | synchronized(Apollo.get().mStickyEventMap) {
268 | //普通事件的被观察者
269 | val flowable = Apollo.Companion.toFlowable(tags, eventType)
270 |
271 | val stickyEvents = java.util.ArrayList()
272 | for (tag in tags) {
273 | //sticky事件
274 | val event = Apollo.get().mStickyEventMap[tag]
275 | if (event != null) {
276 | Apollo.get().mStickyEventMap[tag]?.let { stickyEvents.add(it) }
277 | }
278 | }
279 |
280 | if (!stickyEvents.isEmpty()) {
281 | //合并事件序列
282 | return Flowable.fromIterable(stickyEvents)
283 | .flatMap { event -> Flowable.just(eventType.cast(event.data)) }.mergeWith(flowable)
284 |
285 | } else {
286 | return flowable
287 | }
288 | }
289 | }
290 |
291 | @JvmStatic
292 | fun getSchedulerProvider(): SchedulerProvider = Apollo.get().mSchedulerProvider
293 |
294 | @JvmStatic
295 | fun getContext(): Any = Apollo.get().mContext
296 |
297 |
298 | /**
299 | * ipc转发event
300 | */
301 | @JvmStatic
302 | fun transfer(event: Event) = synchronized(Apollo.get().mStickyEventMap) {
303 | if (Apollo.get().mIPCEnable) {
304 | if (event.isSticky) {
305 | Apollo.get().mStickyEventMap.put(event.tag, event)
306 | }
307 | Apollo.get().mFlowableProcessor.onNext(event)
308 | }
309 | }
310 |
311 | @JvmStatic
312 | fun emit(tag: String) = synchronized(Apollo.get().mStickyEventMap) {
313 | Apollo.Companion.emit(tag, Any(), false)
314 | }
315 |
316 | @JvmStatic
317 | fun emit(tag: String, actual: Any = Any()) = synchronized(Apollo.get().mStickyEventMap) {
318 | Apollo.Companion.emit(tag, actual, false)
319 | }
320 |
321 | @JvmStatic
322 | fun emit(tag: String, sticky: Boolean = false) = synchronized(Apollo.get().mStickyEventMap) {
323 | Apollo.Companion.emit(tag, Any(), sticky)
324 | }
325 |
326 | @JvmStatic
327 | fun emit(tag: String, actual: Any = Any(), sticky: Boolean = false) = synchronized(Apollo.get().mStickyEventMap) {
328 | val event = Event(tag, actual, ProcessUtil.getPid(), sticky)
329 | if (sticky) {
330 | Apollo.get().mStickyEventMap.put(tag, event)
331 | }
332 | Apollo.get().mFlowableProcessor.onNext(event)
333 |
334 | //推送消息到其他进程
335 | if (Apollo.get().mIPCEnable) {
336 |
337 | if (Apollo.get().mIsApolloBinderClassNotFound) {
338 | throw Exception("the ApolloBinderGeneratorImpl class is not found which is generated at compile time")
339 | }
340 |
341 | if (Apollo.get().mIsIPCModuleClassNotFound) {
342 | throw Exception("the ApolloProcessEventReceiver class is not found which belong to ipc module,you must depend on com.github.lsxiao.Apollo:ipc:latest")
343 | }
344 |
345 | Apollo.get().mApolloBinderGenerator.broadcastEvent(event)
346 | }
347 |
348 | }
349 |
350 | @JvmStatic
351 | fun removeStickyEvent(vararg tags: String) = tags.forEach { tag ->
352 | synchronized(Apollo.get().mStickyEventMap) {
353 | Apollo.get().mStickyEventMap.remove(tag)
354 | }
355 | }
356 |
357 | @JvmStatic
358 | fun removeAllStickyEvent() = Apollo.get().mStickyEventMap.clear()
359 |
360 |
361 | /**
362 | * 根据tag和eventType获取指定类型的Sticky事件
363 | */
364 | @JvmStatic
365 | fun getStickyEvent(tag: String, eventType: Class): T? {
366 | synchronized(Apollo.get().mStickyEventMap) {
367 | val o = Apollo.get().mStickyEventMap[tag]?.data as Any
368 | if (o.javaClass.canonicalName == eventType.canonicalName) {
369 | return eventType.cast(o)
370 | }
371 | }
372 | return null
373 | }
374 |
375 | /**
376 | * 根据tag获取Sticky事件
377 | */
378 | @JvmStatic
379 | fun getStickyEvent(tag: String): Any? {
380 | synchronized(Apollo.get().mStickyEventMap) {
381 | return if (Apollo.get().mStickyEventMap[tag] == null) null else Apollo.get().mStickyEventMap[tag]?.data
382 | }
383 | }
384 | }
385 |
386 | }
--------------------------------------------------------------------------------
/processor/src/main/java/com/lsxiao/apllo/processor/CodeGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.lsxiao.apllo.processor
2 |
3 | import com.lsxiao.apollo.core.Apollo
4 | import com.lsxiao.apollo.core.contract.ApolloBinder
5 | import com.lsxiao.apollo.core.contract.ApolloBinderGenerator
6 | import com.lsxiao.apollo.core.entity.ApolloBinderImpl
7 | import com.lsxiao.apollo.core.entity.Event
8 | import com.lsxiao.apollo.core.entity.SchedulerProvider
9 | import com.squareup.javapoet.*
10 | import io.reactivex.BackpressureStrategy
11 | import io.reactivex.subscribers.DisposableSubscriber
12 | import java.io.IOException
13 | import java.util.*
14 | import javax.annotation.processing.Filer
15 | import javax.lang.model.element.Modifier
16 | import javax.lang.model.element.TypeElement
17 | import javax.lang.model.element.VariableElement
18 | import javax.lang.model.type.DeclaredType
19 | import javax.lang.model.type.TypeKind
20 | import javax.lang.model.type.TypeMirror
21 |
22 |
23 | /**
24 | * write with Apollo
25 | * author:lsxiao
26 | * date:2017-04-22 18:00
27 | * github:https://github.com/lsxiao
28 | * zhihu:https://zhihu.com/people/lsxiao
29 | */
30 |
31 | class CodeGenerator private constructor(private val apolloDescriptors: ArrayList, private val mFiler: Filer) {
32 |
33 | companion object {
34 | private val GENERATE_PACKAGE_NAME = "com.lsxiao.apollo.generate"
35 | private val GENERATE_CLASS_NAME = "ApolloBinderGeneratorImpl"
36 | private val SINGLE_INSTANCE_PARAM_NAME = "sInstance"
37 | private val SINGLE_INSTANCE_METHOD_NAME = "instance"
38 | private val SUBSCRIBER_BINDER_LOCAL_PARAM_NAME = "apolloBinder"
39 | private val GENERATE_METHOD_BIND_OBJECT_NAME = "bindObject"
40 | private val EVENT_PARAM_NAME = "event"
41 |
42 | private val SUBSCRIBER_LOCAL_NAME = "subscriber"
43 | private val TO_FLOWABLE_STICKY_METHOD_NAME = "toFlowableSticky"
44 | private val TO_FLOWABLE_METHOD_NAME = "toFlowable"
45 |
46 |
47 | fun create(apolloDescriptors: ArrayList, filer: Filer): CodeGenerator = CodeGenerator(apolloDescriptors, filer)
48 | }
49 |
50 | fun generate() = createJavaFile()
51 |
52 | private fun createJavaFile() = try {
53 | getBinderGeneratorJavaFile().writeTo(mFiler)
54 | } catch (e: IOException) {
55 | e.printStackTrace()
56 | }
57 |
58 | private fun getBinderGeneratorJavaFile(): JavaFile = JavaFile
59 | .builder(GENERATE_PACKAGE_NAME, getGeneratorTypeSpec())
60 | .addStaticImport(SchedulerProvider.Tag.MAIN)
61 | .addStaticImport(SchedulerProvider.Tag.IO)
62 | .addStaticImport(SchedulerProvider.Tag.COMPUTATION)
63 | .addStaticImport(SchedulerProvider.Tag.NEW)
64 | .addStaticImport(SchedulerProvider.Tag.SINGLE)
65 | .addStaticImport(SchedulerProvider.Tag.TRAMPOLINE)
66 | .build()
67 |
68 | /**
69 | * public final class ApolloBinderGeneratorImpl implements ApolloBinderGenerator {
70 | * ...
71 | * }
72 | */
73 | private fun getGeneratorTypeSpec(): TypeSpec = TypeSpec
74 | .classBuilder(GENERATE_CLASS_NAME)
75 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
76 | .addSuperinterface(ApolloBinderGenerator::class.java)
77 | .addField(getSingleInstanceFileSpec())
78 | .addMethod(getBroadcastEventFunctionMethodSpec())
79 | .addMethod(getSingleInstanceMethodSpec())
80 | .addMethod(getGenerateFunctionMethodSpec())
81 | .build()
82 |
83 | /**
84 | * private static ApolloBinderGenerator sInstance;
85 | */
86 | private fun getSingleInstanceFileSpec(): FieldSpec = FieldSpec
87 | .builder(ApolloBinderGenerator::class.java, SINGLE_INSTANCE_PARAM_NAME, Modifier.PRIVATE, Modifier.STATIC)
88 | .build()
89 |
90 | /**
91 | * public static synchronized ApolloBinderGenerator instance() {
92 | * if (null == sInstance) {
93 | * sInstance = new ApolloBinderGeneratorImpl();
94 | * }
95 | * return sInstance;
96 | * }
97 | */
98 | private fun getSingleInstanceMethodSpec(): MethodSpec = MethodSpec.methodBuilder(SINGLE_INSTANCE_METHOD_NAME)
99 | .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.SYNCHRONIZED)
100 | .returns(ApolloBinderGenerator::class.java)
101 | .beginControlFlow("if (null == $SINGLE_INSTANCE_PARAM_NAME)")
102 | .addStatement("$SINGLE_INSTANCE_PARAM_NAME = new $GENERATE_CLASS_NAME()")
103 | .endControlFlow()
104 | .addStatement("return $SINGLE_INSTANCE_PARAM_NAME")
105 | .build()
106 |
107 | /**
108 | * public void broadcastEvent(final Event event) {
109 | * if(com.lsxiao.apollo.core.Apollo.getContext()==null||!(com.lsxiao.apollo.core.Apollo.getContext() instanceof android.content.Context)) {
110 | * return;
111 | * }
112 | * ...
113 | * return;
114 | * }
115 | */
116 | private fun getBroadcastEventFunctionMethodSpec(): MethodSpec {
117 | val builder = MethodSpec.methodBuilder("broadcastEvent")
118 | .addModifiers(Modifier.PUBLIC)
119 | .addAnnotation(Override::class.java)
120 | .addParameter(Event::class.java, EVENT_PARAM_NAME, Modifier.FINAL)
121 | .beginControlFlow("if(${getContext()}==null||!(${getContext()} instanceof android.content.Context))")
122 | .addStatement("return")
123 | .endControlFlow()
124 | .addCode(getSendIntentCodeBlock())
125 |
126 | return builder.addStatement("return").build()
127 | }
128 |
129 |
130 | /**
131 | *
132 | * android.content.Intent intent = new android.content.Intent("apollo");
133 | * android.content.Context context =(android.content.Context)com.lsxiao.apollo.core.Apollo.getContext();
134 | * intent.putExtra("event", event);
135 | * context.sendBroadcast(intent);
136 | */
137 | private fun getSendIntentCodeBlock(): CodeBlock = CodeBlock.builder()
138 | .addStatement("android.content.Intent intent = new android.content.Intent(\"apollo\")")
139 | .addStatement("android.content.Context context =(android.content.Context)${getContext()}")
140 | .addStatement("intent.putExtra(\"event\", ${getSerializer()}.serialize($EVENT_PARAM_NAME))")
141 | .addStatement("context.sendBroadcast(intent)")
142 | .build()
143 |
144 | /**
145 | * @Override
146 | * public ApolloBinder generate(Object object) {
147 | * final ApolloBinderImpl apolloBinder = new ApolloBinderImpl();
148 | * ...
149 | * return apolloBinder;
150 | * }
151 | */
152 | private fun getGenerateFunctionMethodSpec(): MethodSpec {
153 | val builder = MethodSpec.methodBuilder("generate")
154 | .addModifiers(Modifier.PUBLIC)
155 | .addAnnotation(Override::class.java)
156 | .returns(ApolloBinder::class.java)
157 | .addParameter(Any::class.java, GENERATE_METHOD_BIND_OBJECT_NAME, Modifier.FINAL)
158 | .addStatement("final \$T $SUBSCRIBER_BINDER_LOCAL_PARAM_NAME = new \$T($GENERATE_METHOD_BIND_OBJECT_NAME)", ApolloBinderImpl::class.java, ApolloBinderImpl::class.java)
159 |
160 | apolloDescriptors.forEach {
161 | getSingleBinderStatement(builder, it)
162 | }
163 |
164 | return builder.addStatement("return $SUBSCRIBER_BINDER_LOCAL_PARAM_NAME").build()
165 | }
166 |
167 | /**
168 | * if (bindObject.getClass().isAssignableFrom(...class)) {
169 | * apolloBinder.add(Apollo.get().toFlowable(new String[]{...}).subscribeOn(Apollo.get().getSchedulerProvider().get(...)).observeOn(...).subscribeWith(...))
170 | * }
171 | */
172 | private fun getSingleBinderStatement(builder: MethodSpec.Builder, descriptor: ApolloDescriptor) {
173 | val clazzType = descriptor.methodElement.enclosingElement.asType().toString().replace(Regex("<.*>"), "")
174 |
175 | builder.beginControlFlow("if($clazzType.class.isAssignableFrom($GENERATE_METHOD_BIND_OBJECT_NAME.getClass()))")
176 | .addStatement("$SUBSCRIBER_BINDER_LOCAL_PARAM_NAME.add(" +
177 | getApollo() +
178 | getToFlowableCode(descriptor) +
179 | getEventOnceReceiveCode(descriptor) +
180 | getBackpressure(descriptor) +
181 | getSubscribeOnMethodCode(descriptor) +
182 | getObserveOnMethodCode(descriptor) +
183 | getSubscribeWithCode(descriptor) +
184 | ")",
185 | Apollo::class.java
186 | )
187 | .endControlFlow()
188 | }
189 |
190 | /**
191 | * .toFlowable(new String[...tags])
192 | */
193 | private fun getToFlowableCode(descriptor: ApolloDescriptor): CodeBlock {
194 | val toFlowable: String = if (descriptor.isSticky) {
195 | TO_FLOWABLE_STICKY_METHOD_NAME
196 | } else {
197 | TO_FLOWABLE_METHOD_NAME
198 | }
199 | return CodeBlock.of(".$toFlowable(${getTagsStringArrayCode(descriptor)})")
200 | }
201 |
202 | private fun getTagsStringArrayCode(descriptor: ApolloDescriptor): CodeBlock = CodeBlock.of("new String[]{${Util.split(descriptor.tags, ",")}}")
203 |
204 | /**
205 | * .onBackpressureBuffer()
206 | * .onBackpressureDrop()
207 | * .
208 | */
209 | private fun getBackpressure(descriptor: ApolloDescriptor): CodeBlock {
210 | val onBackpressure: String = when (descriptor.backpressureStrategy) {
211 | BackpressureStrategy.BUFFER -> ".onBackpressureBuffer()"
212 | BackpressureStrategy.DROP -> ".onBackpressureDrop()"
213 | BackpressureStrategy.LATEST -> ".onBackpressureLatest()"
214 | else -> {
215 | ""
216 | }
217 | }
218 | return CodeBlock.of(onBackpressure)
219 | }
220 |
221 | /**
222 | * Apollo.get().getSchedulerProvider().get(descriptor.subscribeOn)
223 | */
224 | private fun getSubscribeOnMethodCode(descriptor: ApolloDescriptor): CodeBlock = CodeBlock.of(".subscribeOn(${getSchedulerCode(descriptor.subscribeOn)})")
225 |
226 | /**
227 | * Apollo.get().getSchedulerProvider().get(descriptor.observeOn)
228 | */
229 | private fun getObserveOnMethodCode(descriptor: ApolloDescriptor): CodeBlock = CodeBlock.of(".observeOn(${getSchedulerCode(descriptor.observeOn)})")
230 |
231 | /**
232 | * Apollo.get().getSchedulerProvider().get(...)
233 | */
234 | private fun getSchedulerCode(tag: SchedulerProvider.Tag): CodeBlock = CodeBlock.of("${getApollo()}.getSchedulerProvider().get(${tag.name})")
235 |
236 | /**
237 | * Apollo.get()
238 | */
239 | private fun getApollo(): CodeBlock = CodeBlock.of("\$T", Apollo::class.java)
240 |
241 | /**
242 | * Apollo.getContext()
243 | */
244 | private fun getContext(): CodeBlock = CodeBlock.of("\$T.getContext()", Apollo::class.java)
245 |
246 |
247 | /**
248 | * Apollo.getContext()
249 | */
250 | private fun getSerializer(): CodeBlock = CodeBlock.of("\$T.getSerializer()", Apollo::class.java)
251 |
252 | /**
253 | * .subscribeWith(new DisposableSubscriber