SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Replace EventBus with
RxJava/RxAndroid
Hiroyuki Kusu ( @hkusu_ )
株式会社ゆめみ
2016/02/17 potatotips #26
Android 以外も色々やります。最近は主に JavaScript
( Node.js + ES2015 ) を書いてます。
greenrobot/EventBus
⇒ Replace with RxJava(RxAndroid)
app/build.gradle
dependencies {
// ...
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
}
public class RxEventBus {
private final Subject<Object, Object> subject
= new SerializedSubject<>(PublishSubject.create());
public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.subscribe(handler);
}
public void post(Object event) {
subject.onNext(event);
}
}
RxEventBus.java
public class RxEventBusProvider {
private static final RxEventBus rxEventBus = new RxEventBus();
public static RxEventBus provide(){
return rxEventBus;
}
}
RxEventBusProvider.java
※ providing the singleton instance
RxEventBus rxEventBus = RxEventBusProvider.provide();
rxEventBus.post(new ChangedEvent());
rxEventBus.onEvent(ChangedEvent.class, event -> {
// something..
});
※ applying Java8 & Retrolambda
Getting instance
Publish
Subscribe
Subscription subscription;
// ...
subscription = rxEventBus.onEvent(ChangedEvent.class, event -> {
// something..
});
// ...
subscription.unsubscribe();
Unsubscribe ( order not to leak)
Tips
public class RxEventBus {
private final Subject<Object, Object> subject
= new SerializedSubject<>(PublishSubject.create());
public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.subscribe(handler);
}
public <T> Subscription onEventMainThread(Class<T> clazz, Action1<T> handler) {
return subject
.ofType(clazz)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(handler);
}
public void post(Object event) {
subject.onNext(event);
}
}
Subscribing in the main thread
public class ChangedEvent {
private int id;
public ChangedEvent(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
rxEventBus.post(new ChangedEvent(99));
rxEventBus.onEvent(ChangedEvent.class, event -> {
int id = event.getId();
// something..
});
Getting a value from the event
rxEventBus.onEvent(TodoRepository.ChangedEvent.class, event -> {
// something..
});
Create event as an inner class of the class to
publish (or subscribe) the event.
Because, it is unclear to post the event from
where(or to where).
Appendix
Providing a singleton instance
in Dagger2
@Module
public class AppModule {
@Provides
@Singleton
public RxEventBus provideRxEventBus(){
return new RxEventBus();
}
}
AppModule.java
@Component(modules = AppModule.class)
public interface AppComponent {
RxEventBus provideRxEventBus();
}
AppComponent.java
Getting instance
AppComponent appComponent = DaggerAppComponent.create();
// ...
RxEventBus rxEventBus = appComponent.provideRxEventBus();
In this example, Dagger2 looks redundant , but
redundant description can be reduced by
@inject annotation to the constructor.
See https://github.com/hkusu/android-dagger-rxjava-sample .
Sample code
hkusu/android-dagger-rxjava-sample
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using dockerPavel Rabetski
 
Maintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood StyleMaintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood StyleRebecca Wirfs-Brock
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingMitinPavel
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React NativeMuhammed Demirci
 
MVC In Depth, part 2, Tommy Maintz
MVC In Depth, part 2, Tommy MaintzMVC In Depth, part 2, Tommy Maintz
MVC In Depth, part 2, Tommy MaintzSencha
 
Infracoders VII - Someone is Watching You
Infracoders VII   - Someone is Watching YouInfracoders VII   - Someone is Watching You
Infracoders VII - Someone is Watching YouOliver Moser
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
User controls
User controlsUser controls
User controlsaspnet123
 
Effective memory management
Effective memory managementEffective memory management
Effective memory managementDenis Zhuchinski
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Redux as a state container
Redux as a state containerRedux as a state container
Redux as a state containerTahin Rahman
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaFabio Collini
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
Testing Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKTesting Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKFabio Collini
 
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Codemotion
 

Was ist angesagt? (20)

Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using docker
 
Maintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood StyleMaintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood Style
 
Command Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event SourcingCommand Query Responsibility Segregation and Event Sourcing
Command Query Responsibility Segregation and Event Sourcing
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
MVC In Depth, part 2, Tommy Maintz
MVC In Depth, part 2, Tommy MaintzMVC In Depth, part 2, Tommy Maintz
MVC In Depth, part 2, Tommy Maintz
 
Infracoders VII - Someone is Watching You
Infracoders VII   - Someone is Watching YouInfracoders VII   - Someone is Watching You
Infracoders VII - Someone is Watching You
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
Advanced Jquery
Advanced JqueryAdvanced Jquery
Advanced Jquery
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
User controls
User controlsUser controls
User controls
 
Effective memory management
Effective memory managementEffective memory management
Effective memory management
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Redux as a state container
Redux as a state containerRedux as a state container
Redux as a state container
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJava
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
Angular redux
Angular reduxAngular redux
Angular redux
 
Testing Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKTesting Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UK
 
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
 

Andere mochten auch

チュートリアルをリッチにしよう
チュートリアルをリッチにしようチュートリアルをリッチにしよう
チュートリアルをリッチにしようshinya sakemoto
 
AndroidアプリのUI/UX改善例
AndroidアプリのUI/UX改善例AndroidアプリのUI/UX改善例
AndroidアプリのUI/UX改善例Kenichi Kambara
 
5分でわかるText Kit
5分でわかるText Kit5分でわかるText Kit
5分でわかるText KitRyota Hayashi
 
Can we live in a pure Swift world?
Can we live in a pure Swift world?Can we live in a pure Swift world?
Can we live in a pure Swift world?toyship
 
脱swift初心者するための2つのきっかけ
脱swift初心者するための2つのきっかけ脱swift初心者するための2つのきっかけ
脱swift初心者するための2つのきっかけDaiki Mogmet Ito
 
iOS の通信における認証の種類とその取り扱い
iOS の通信における認証の種類とその取り扱いiOS の通信における認証の種類とその取り扱い
iOS の通信における認証の種類とその取り扱いniwatako
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
PUSH通知の許可をよりもらうためのUI考察など
PUSH通知の許可をよりもらうためのUI考察などPUSH通知の許可をよりもらうためのUI考察など
PUSH通知の許可をよりもらうためのUI考察などTsuyoshi Yonemoto
 
iOS Developers Conference Japan 2016
iOS Developers Conference Japan 2016iOS Developers Conference Japan 2016
iOS Developers Conference Japan 2016Tomoki Hasegawa
 
Ambry : Linkedin's Scalable Geo-Distributed Object Store
Ambry : Linkedin's Scalable Geo-Distributed Object StoreAmbry : Linkedin's Scalable Geo-Distributed Object Store
Ambry : Linkedin's Scalable Geo-Distributed Object StoreSivabalan Narayanan
 
Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2Trieu Nguyen
 
React.js and Flux in details
React.js and Flux in detailsReact.js and Flux in details
React.js and Flux in detailsArtyom Trityak
 
Android Design Principles and Popular Patterns
Android Design Principles and Popular PatternsAndroid Design Principles and Popular Patterns
Android Design Principles and Popular PatternsFaiz Malkani
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/FluxKeuller Magalhães
 

Andere mochten auch (20)

チュートリアルをリッチにしよう
チュートリアルをリッチにしようチュートリアルをリッチにしよう
チュートリアルをリッチにしよう
 
AndroidアプリのUI/UX改善例
AndroidアプリのUI/UX改善例AndroidアプリのUI/UX改善例
AndroidアプリのUI/UX改善例
 
動画のあれこれ
動画のあれこれ動画のあれこれ
動画のあれこれ
 
Foreground検知
Foreground検知Foreground検知
Foreground検知
 
5分でわかるText Kit
5分でわかるText Kit5分でわかるText Kit
5分でわかるText Kit
 
Can we live in a pure Swift world?
Can we live in a pure Swift world?Can we live in a pure Swift world?
Can we live in a pure Swift world?
 
脱swift初心者するための2つのきっかけ
脱swift初心者するための2つのきっかけ脱swift初心者するための2つのきっかけ
脱swift初心者するための2つのきっかけ
 
iOS の通信における認証の種類とその取り扱い
iOS の通信における認証の種類とその取り扱いiOS の通信における認証の種類とその取り扱い
iOS の通信における認証の種類とその取り扱い
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
PUSH通知の許可をよりもらうためのUI考察など
PUSH通知の許可をよりもらうためのUI考察などPUSH通知の許可をよりもらうためのUI考察など
PUSH通知の許可をよりもらうためのUI考察など
 
iOS Developers Conference Japan 2016
iOS Developers Conference Japan 2016iOS Developers Conference Japan 2016
iOS Developers Conference Japan 2016
 
Ambry : Linkedin's Scalable Geo-Distributed Object Store
Ambry : Linkedin's Scalable Geo-Distributed Object StoreAmbry : Linkedin's Scalable Geo-Distributed Object Store
Ambry : Linkedin's Scalable Geo-Distributed Object Store
 
Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2
 
Choice Paralysis
Choice ParalysisChoice Paralysis
Choice Paralysis
 
About Flux
About FluxAbout Flux
About Flux
 
React.js and Flux in details
React.js and Flux in detailsReact.js and Flux in details
React.js and Flux in details
 
Android Design Principles and Popular Patterns
Android Design Principles and Popular PatternsAndroid Design Principles and Popular Patterns
Android Design Principles and Popular Patterns
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/Flux
 
Flux architecture
Flux architectureFlux architecture
Flux architecture
 

Ähnlich wie 【Potatotips #26】Replace EventBus with RxJava/RxAndroid

From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptMaurice De Beijer [MVP]
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJSRavi Mone
 
React Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかReact Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかYukiya Nakagawa
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
The art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsThe art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsBartłomiej Pisulak
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing ComplexityRyan Anklam
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptMaurice De Beijer [MVP]
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
 
Qt & Webkit
Qt & WebkitQt & Webkit
Qt & WebkitQT-day
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 

Ähnlich wie 【Potatotips #26】Replace EventBus with RxJava/RxAndroid (20)

From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java script
 
React 101
React 101React 101
React 101
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJS
 
React Native Androidはなぜ動くのか
React Native Androidはなぜ動くのかReact Native Androidはなぜ動くのか
React Native Androidはなぜ動くのか
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
The art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid AppsThe art of Building Bridges for Android Hybrid Apps
The art of Building Bridges for Android Hybrid Apps
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScript
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Qt & Webkit
Qt & WebkitQt & Webkit
Qt & Webkit
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 

Mehr von Hiroyuki Kusu

【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する
【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する
【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発するHiroyuki Kusu
 
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話Hiroyuki Kusu
 
【Potatotips #30】RxJavaを活用する3つのユースケース
【Potatotips #30】RxJavaを活用する3つのユースケース【Potatotips #30】RxJavaを活用する3つのユースケース
【Potatotips #30】RxJavaを活用する3つのユースケースHiroyuki Kusu
 
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意するHiroyuki Kusu
 
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲するHiroyuki Kusu
 
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)Hiroyuki Kusu
 
【eLV勉強会】AngularJSでのモバイルフロントエンド開発
【eLV勉強会】AngularJSでのモバイルフロントエンド開発【eLV勉強会】AngularJSでのモバイルフロントエンド開発
【eLV勉強会】AngularJSでのモバイルフロントエンド開発Hiroyuki Kusu
 
エンジニアにMacを薦める理由
エンジニアにMacを薦める理由エンジニアにMacを薦める理由
エンジニアにMacを薦める理由Hiroyuki Kusu
 
ソーシャルアプリで人を熱中させる要素を説明する一枚絵
ソーシャルアプリで人を熱中させる要素を説明する一枚絵ソーシャルアプリで人を熱中させる要素を説明する一枚絵
ソーシャルアプリで人を熱中させる要素を説明する一枚絵Hiroyuki Kusu
 
【ABC2014Spring LT】AngularJSでWEBアプリ開発
【ABC2014Spring LT】AngularJSでWEBアプリ開発【ABC2014Spring LT】AngularJSでWEBアプリ開発
【ABC2014Spring LT】AngularJSでWEBアプリ開発Hiroyuki Kusu
 

Mehr von Hiroyuki Kusu (10)

【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する
【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する
【東京Node学園祭2016】Node.js × Babel で AWS Lambda アプリケーションを開発する
 
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話
【YAPC::Asia Hachioji 2016】ES2015のclassでアプリケーションを書いてみた話
 
【Potatotips #30】RxJavaを活用する3つのユースケース
【Potatotips #30】RxJavaを活用する3つのユースケース【Potatotips #30】RxJavaを活用する3つのユースケース
【Potatotips #30】RxJavaを活用する3つのユースケース
 
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する
【Potatotips #23】手軽にHTTPでJSONにアクセスできる環境を用意する
 
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する
【Roppongi.aar #1】Activity/FragmentからControllerへ処理を委譲する
 
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)
【DroidKaigi2015】初学者に嬉しいAndroid開発環境(あとMVCとか)
 
【eLV勉強会】AngularJSでのモバイルフロントエンド開発
【eLV勉強会】AngularJSでのモバイルフロントエンド開発【eLV勉強会】AngularJSでのモバイルフロントエンド開発
【eLV勉強会】AngularJSでのモバイルフロントエンド開発
 
エンジニアにMacを薦める理由
エンジニアにMacを薦める理由エンジニアにMacを薦める理由
エンジニアにMacを薦める理由
 
ソーシャルアプリで人を熱中させる要素を説明する一枚絵
ソーシャルアプリで人を熱中させる要素を説明する一枚絵ソーシャルアプリで人を熱中させる要素を説明する一枚絵
ソーシャルアプリで人を熱中させる要素を説明する一枚絵
 
【ABC2014Spring LT】AngularJSでWEBアプリ開発
【ABC2014Spring LT】AngularJSでWEBアプリ開発【ABC2014Spring LT】AngularJSでWEBアプリ開発
【ABC2014Spring LT】AngularJSでWEBアプリ開発
 

Kürzlich hochgeladen

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Kürzlich hochgeladen (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

【Potatotips #26】Replace EventBus with RxJava/RxAndroid

  • 1. Replace EventBus with RxJava/RxAndroid Hiroyuki Kusu ( @hkusu_ ) 株式会社ゆめみ 2016/02/17 potatotips #26
  • 4. app/build.gradle dependencies { // ... compile 'io.reactivex:rxjava:1.1.0' compile 'io.reactivex:rxandroid:1.1.0' }
  • 5. public class RxEventBus { private final Subject<Object, Object> subject = new SerializedSubject<>(PublishSubject.create()); public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) { return subject .ofType(clazz) .subscribe(handler); } public void post(Object event) { subject.onNext(event); } } RxEventBus.java
  • 6. public class RxEventBusProvider { private static final RxEventBus rxEventBus = new RxEventBus(); public static RxEventBus provide(){ return rxEventBus; } } RxEventBusProvider.java ※ providing the singleton instance
  • 7. RxEventBus rxEventBus = RxEventBusProvider.provide(); rxEventBus.post(new ChangedEvent()); rxEventBus.onEvent(ChangedEvent.class, event -> { // something.. }); ※ applying Java8 & Retrolambda Getting instance Publish Subscribe
  • 8. Subscription subscription; // ... subscription = rxEventBus.onEvent(ChangedEvent.class, event -> { // something.. }); // ... subscription.unsubscribe(); Unsubscribe ( order not to leak)
  • 10. public class RxEventBus { private final Subject<Object, Object> subject = new SerializedSubject<>(PublishSubject.create()); public <T> Subscription onEvent(Class<T> clazz, Action1<T> handler) { return subject .ofType(clazz) .subscribe(handler); } public <T> Subscription onEventMainThread(Class<T> clazz, Action1<T> handler) { return subject .ofType(clazz) .observeOn(AndroidSchedulers.mainThread()) .subscribe(handler); } public void post(Object event) { subject.onNext(event); } } Subscribing in the main thread
  • 11. public class ChangedEvent { private int id; public ChangedEvent(int id) { this.id = id; } public int getId() { return id; } } rxEventBus.post(new ChangedEvent(99)); rxEventBus.onEvent(ChangedEvent.class, event -> { int id = event.getId(); // something.. }); Getting a value from the event
  • 12. rxEventBus.onEvent(TodoRepository.ChangedEvent.class, event -> { // something.. }); Create event as an inner class of the class to publish (or subscribe) the event. Because, it is unclear to post the event from where(or to where).
  • 13. Appendix Providing a singleton instance in Dagger2
  • 14. @Module public class AppModule { @Provides @Singleton public RxEventBus provideRxEventBus(){ return new RxEventBus(); } } AppModule.java @Component(modules = AppModule.class) public interface AppComponent { RxEventBus provideRxEventBus(); } AppComponent.java
  • 15. Getting instance AppComponent appComponent = DaggerAppComponent.create(); // ... RxEventBus rxEventBus = appComponent.provideRxEventBus(); In this example, Dagger2 looks redundant , but redundant description can be reduced by @inject annotation to the constructor. See https://github.com/hkusu/android-dagger-rxjava-sample .