SlideShare a Scribd company logo
1 of 66
Download to read offline
Subject 入門
Rx Ja Night 2016 #1
2016-02-25
• 白山 文彦
• 株式会社マナボ 技術者
Subject とはなんだろうか?
/**

* Represents an object that is both an Observable and an Observer.

*/

public abstract class Subject<T, R> extends Observable<R> implements Observer<T> {

protected Subject(OnSubscribe<R> onSubscribe) {

super(onSubscribe);

}
...
}
/**

* Represents an object that is both an Observable and an Observer.

*/

public abstract class Subject<T, R> extends Observable<R> implements Observer<T> {

protected Subject(OnSubscribe<R> onSubscribe) {

super(onSubscribe);

}
...
}
Observer でもあり
Observable でもある
ObserverとしてObservableをsubscribeできる
Observableとして他のObserverからsubscribeされる
from wikimedia commons
Source Observable
Subject
Observer
最も基本的な例
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
create
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
subscribe
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
bypass
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
bypass
値がObservableの外から
来ていることに注目!
HOT Observable
と呼ばれたりする
Subject の種類
• PublishSubject
• BehaviorSubject
• AsyncSubject
• ReplaySubject
PublishSubject
• 最も基本的なSubject
• subscribeしたObserverに後続のイベントをその
ままバイパスする
ここでsubscribeしたObserverは
3つとも受け取る
ここでsubscribeしたObserverはこの1つだけ
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
observer
PublishSubject<String> subject = PublishSubject.create();



subject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);



try {

subject.onNext("FOO");

subject.onNext("BAR");

subject.onNext("BAZ");

subject.onCompleted();

} catch (Exception e) {

subject.onError(e);

}
bypass
BehaviorSubject
• 直前の値(ない場合は初期値)をキャッシュし、
Observerに即座に返すSubject
• 後続のイベントはそのままバイパスする
Default Value
Most Recent Value
Observable<String> observable = Observable.just("FOO", "BAR", "BAZ");


BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");

observable.subscribe(

behaviorSubject::onNext

);

behaviorSubject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);
Observable<String> observable = Observable.just("FOO", "BAR", "BAZ");


BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");

observable.subscribe(

behaviorSubject::onNext

);

behaviorSubject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);
FOO, BAR, BAZ...
Observable<String> observable = Observable.just("FOO", "BAR", "BAZ");


BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");

observable.subscribe(

behaviorSubject::onNext

);

behaviorSubject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);
BAZ
Observable<String> observable = Observable.just("FOO", "BAR", "BAZ");


BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");

observable.subscribe(

behaviorSubject::onNext

);

behaviorSubject.subscribe(

val -> Log.i(TAG, val),

error -> Log.e(TAG, error.getMessage(), error)

);
BAZ
AsyncSubject
• Subject#onCompletedが呼ばれたらその直前の
onNext(T)をObserverに1回だけ渡す
• Subject#onNextが何度呼ばれてもonCompleted
まではObserverには何も渡らない
• REST通信など、onNext, onCompletedが1セッ
トみたいなケースで便利そう
Last Value
Observable<String> sourceObservable = Observable.just("ONE");

AsyncSubject<String> asyncSubject = AsyncSubject.create();

sourceObservable.subscribe(

data -> {

asyncSubject.onNext(data);

asyncSubject.onCompleted();

},

error -> Log.e(TAG, error.getMessage(), error)

);



asyncSubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
Observable<String> sourceObservable = Observable.just("ONE");

AsyncSubject<String> asyncSubject = AsyncSubject.create();

sourceObservable.subscribe(

data -> {

asyncSubject.onNext(data);

asyncSubject.onCompleted();

},

error -> Log.e(TAG, error.getMessage(), error)

);



asyncSubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
ONE
Observable<String> sourceObservable = Observable.just("ONE");

AsyncSubject<String> asyncSubject = AsyncSubject.create();

sourceObservable.subscribe(

data -> {

asyncSubject.onNext(data);

asyncSubject.onCompleted();

},

error -> Log.e(TAG, error.getMessage(), error)

);



asyncSubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
ONE
ReplaySubject
• subscribeしたObservableから送出された値をす
べてキャッシュし、Observerがsubscribeしてき
たらそれをすべて渡すようなSubject
• 後続のイベントもそのままバイパスする
Cached Value
Observable<String> sourceObservable
= Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");

ReplaySubject<String> replaySubject = ReplaySubject.create();

sourceObservable.subscribe(

replaySubject::onNext

);



replaySubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
Observable<String> sourceObservable
= Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");

ReplaySubject<String> replaySubject = ReplaySubject.create();

sourceObservable.subscribe(

replaySubject::onNext

);



replaySubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
cache
Observable<String> sourceObservable
= Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");

ReplaySubject<String> replaySubject = ReplaySubject.create();

sourceObservable.subscribe(

replaySubject::onNext

);



replaySubject.subscribe(

data -> Log.i(TAG, data),

error -> Log.e(TAG, error.getMessage(), error)

);
ONE, TWO, THREE, FOUR, FIVE
Subject の応用例
EventBus
WTF...
public class RxEventBus {

private final Subject<Object, Object> bus
= new SerializedSubject<>(PublishSubject.create());



public void post(Object event) {

bus.onNext(event);

}



public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {

return bus.ofType(clazz).subscribe(onNext);

}

}
public class RxEventBus {

private final Subject<Object, Object> bus
= new SerializedSubject<>(PublishSubject.create());



public void post(Object event) {

bus.onNext(event);

}



public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {

return bus.ofType(clazz).subscribe(onNext);

}

}
Thread Safe Subject
public class RxEventBus {

private final Subject<Object, Object> bus
= new SerializedSubject<>(PublishSubject.create());



public void post(Object event) {

bus.onNext(event);

}



public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {

return bus.ofType(clazz).subscribe(onNext);

}

}
bypass
public class BusProvider {

private static final RxEventBus eventBus = new RxEventBus();



private BusProvider() {

}



public static RxEventBus getInstance() {

return eventBus;

}

}

Singleton
public class ItemSelectEvent {

private int position;



public ItemSelectEvent(int position) {

this.position = position;

}



public int getPosition() {

return position;

}

}

Simple Event
public class Adapter extends RecyclerView.Adapter<ViewHolder> {

private LayoutInflater layoutInflater;

private List<String> texts;



public Adapter(Context context) {

layoutInflater = LayoutInflater.from(context);

texts = new ArrayList<>();

texts.add("あああああああああああ");

...

}



@Override

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View v = layoutInflater.inflate(R.layout.list_item, parent, false);

ViewHolder viewHolder = new ViewHolder(v);

viewHolder.itemView.setOnClickListener(view -> {

int position = viewHolder.getAdapterPosition();

if (position != RecyclerView.NO_POSITION) {

BusProvider.getInstance().post(new ItemSelectEvent(position));

}

});

return viewHolder;

}



@Override

public void onBindViewHolder(ViewHolder holder, int position) {

holder.bind(texts.get(position));

}



@Override

public int getItemCount() {

return texts.size();

}

}
public class Adapter extends RecyclerView.Adapter<ViewHolder> {

private LayoutInflater layoutInflater;

private List<String> texts;



public Adapter(Context context) {

layoutInflater = LayoutInflater.from(context);

texts = new ArrayList<>();

texts.add("あああああああああああ");

...

}



@Override

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View v = layoutInflater.inflate(R.layout.list_item, parent, false);

ViewHolder viewHolder = new ViewHolder(v);

viewHolder.itemView.setOnClickListener(view -> {

int position = viewHolder.getAdapterPosition();

if (position != RecyclerView.NO_POSITION) {

BusProvider.getInstance().post(new ItemSelectEvent(position));

}

});

return viewHolder;

}



@Override

public void onBindViewHolder(ViewHolder holder, int position) {

holder.bind(texts.get(position));

}



@Override

public int getItemCount() {

return texts.size();

}

}
ottoとほぼ同じ!
public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();



@Bind(R.id.recycler_view)

RecyclerView recyclerView;



private Subscription subscription;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ButterKnife.bind(this);



recyclerView.setLayoutManager(new LinearLayoutManager(this));

recyclerView.setHasFixedSize(true);

recyclerView.setItemAnimator(new DefaultItemAnimator());

recyclerView.setAdapter(new Adapter(this));

}





@Override

protected void onResume() {

super.onResume();

subscription = BusProvider.getInstance().subscribe(

ItemSelectEvent.class,

e -> Toast.makeText(this, "position: " + e.getPosition(), Toast.LENGTH_SHORT).show()

);

}



@Override

protected void onPause() {

subscription.unsubscribe();

super.onPause();

}

}
public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();



@Bind(R.id.recycler_view)

RecyclerView recyclerView;



private Subscription subscription;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ButterKnife.bind(this);



recyclerView.setLayoutManager(new LinearLayoutManager(this));

recyclerView.setHasFixedSize(true);

recyclerView.setItemAnimator(new DefaultItemAnimator());

recyclerView.setAdapter(new Adapter(this));

}





@Override

protected void onResume() {

super.onResume();

subscription = BusProvider.getInstance().subscribe(

ItemSelectEvent.class,

e -> Toast.makeText(this, "position: " + e.getPosition(), Toast.LENGTH_SHORT).show()

);

}



@Override

protected void onPause() {

subscription.unsubscribe();

super.onPause();

}

}
ここもそっくり!
https://github.com/srym/RxEventBus
その他TIPS、質疑応答

More Related Content

What's hot

連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyIván López Martín
 
Android Bootstrap
Android BootstrapAndroid Bootstrap
Android Bootstrapdonnfelker
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingMayflower GmbH
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180Mahmoud Samir Fayed
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 

What's hot (20)

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
Solid principles
Solid principlesSolid principles
Solid principles
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with Groovy
 
Android Bootstrap
Android BootstrapAndroid Bootstrap
Android Bootstrap
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
EMFPath
EMFPathEMFPath
EMFPath
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 

Similar to RxJava - Subject 入門

Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiNexus FrontierTech
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivediharintrivedi
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaMatt Stine
 
Testing Kafka - The Developer Perspective
Testing Kafka - The Developer PerspectiveTesting Kafka - The Developer Perspective
Testing Kafka - The Developer Perspectivemaiktoepfer
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 

Similar to RxJava - Subject 入門 (20)

Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
Testing Kafka - The Developer Perspective
Testing Kafka - The Developer PerspectiveTesting Kafka - The Developer Perspective
Testing Kafka - The Developer Perspective
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Php sql-android
Php sql-androidPhp sql-android
Php sql-android
 
Ext J S Observable
Ext J S ObservableExt J S Observable
Ext J S Observable
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 

More from Fumihiko Shiroyama

GCP HTTPロードバランサ運用例
GCP HTTPロードバランサ運用例GCP HTTPロードバランサ運用例
GCP HTTPロードバランサ運用例Fumihiko Shiroyama
 
GDG Tokyo Firebaseを使った Androidアプリ開発
GDG Tokyo Firebaseを使った Androidアプリ開発GDG Tokyo Firebaseを使った Androidアプリ開発
GDG Tokyo Firebaseを使った Androidアプリ開発Fumihiko Shiroyama
 
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリ
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリFirebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリ
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリFumihiko Shiroyama
 
Rxjavaとoptionalで関数型androidしよう
Rxjavaとoptionalで関数型androidしようRxjavaとoptionalで関数型androidしよう
Rxjavaとoptionalで関数型androidしようFumihiko Shiroyama
 
絶対落ちないアプリの作り方
絶対落ちないアプリの作り方絶対落ちないアプリの作り方
絶対落ちないアプリの作り方Fumihiko Shiroyama
 
Ops worksに今後期待するところ
Ops worksに今後期待するところOps worksに今後期待するところ
Ops worksに今後期待するところFumihiko Shiroyama
 

More from Fumihiko Shiroyama (10)

Firebase with Android
Firebase with AndroidFirebase with Android
Firebase with Android
 
GCP HTTPロードバランサ運用例
GCP HTTPロードバランサ運用例GCP HTTPロードバランサ運用例
GCP HTTPロードバランサ運用例
 
GDG Tokyo Firebaseを使った Androidアプリ開発
GDG Tokyo Firebaseを使った Androidアプリ開発GDG Tokyo Firebaseを使った Androidアプリ開発
GDG Tokyo Firebaseを使った Androidアプリ開発
 
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリ
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリFirebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリ
Firebaseで驚くほど簡単に作れるリアルタイムイベントドリブンアプリ
 
AndroidでEither
AndroidでEitherAndroidでEither
AndroidでEither
 
Rxjavaとoptionalで関数型androidしよう
Rxjavaとoptionalで関数型androidしようRxjavaとoptionalで関数型androidしよう
Rxjavaとoptionalで関数型androidしよう
 
絶対落ちないアプリの作り方
絶対落ちないアプリの作り方絶対落ちないアプリの作り方
絶対落ちないアプリの作り方
 
Ops worksに今後期待するところ
Ops worksに今後期待するところOps worksに今後期待するところ
Ops worksに今後期待するところ
 
Wallet api
Wallet apiWallet api
Wallet api
 
Google io 2013_keynote
Google io 2013_keynoteGoogle io 2013_keynote
Google io 2013_keynote
 

Recently uploaded

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 

Recently uploaded (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 

RxJava - Subject 入門

  • 1. Subject 入門 Rx Ja Night 2016 #1 2016-02-25
  • 4. /**
 * Represents an object that is both an Observable and an Observer.
 */
 public abstract class Subject<T, R> extends Observable<R> implements Observer<T> {
 protected Subject(OnSubscribe<R> onSubscribe) {
 super(onSubscribe);
 } ... }
  • 5. /**
 * Represents an object that is both an Observable and an Observer.
 */
 public abstract class Subject<T, R> extends Observable<R> implements Observer<T> {
 protected Subject(OnSubscribe<R> onSubscribe) {
 super(onSubscribe);
 } ... }
  • 10.
  • 15. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 }
  • 16. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } create
  • 17. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } subscribe
  • 18. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } bypass
  • 19. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } bypass 値がObservableの外から 来ていることに注目!
  • 22. • PublishSubject • BehaviorSubject • AsyncSubject • ReplaySubject
  • 25.
  • 28. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } observer
  • 29. PublishSubject<String> subject = PublishSubject.create();
 
 subject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 try {
 subject.onNext("FOO");
 subject.onNext("BAR");
 subject.onNext("BAZ");
 subject.onCompleted();
 } catch (Exception e) {
 subject.onError(e);
 } bypass
  • 32.
  • 35. Observable<String> observable = Observable.just("FOO", "BAR", "BAZ"); 
 BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");
 observable.subscribe(
 behaviorSubject::onNext
 );
 behaviorSubject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 );
  • 36. Observable<String> observable = Observable.just("FOO", "BAR", "BAZ"); 
 BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");
 observable.subscribe(
 behaviorSubject::onNext
 );
 behaviorSubject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 ); FOO, BAR, BAZ...
  • 37. Observable<String> observable = Observable.just("FOO", "BAR", "BAZ"); 
 BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");
 observable.subscribe(
 behaviorSubject::onNext
 );
 behaviorSubject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 ); BAZ
  • 38. Observable<String> observable = Observable.just("FOO", "BAR", "BAZ"); 
 BehaviorSubject<String> behaviorSubject = BehaviorSubject.create("init val");
 observable.subscribe(
 behaviorSubject::onNext
 );
 behaviorSubject.subscribe(
 val -> Log.i(TAG, val),
 error -> Log.e(TAG, error.getMessage(), error)
 ); BAZ
  • 41.
  • 43. Observable<String> sourceObservable = Observable.just("ONE");
 AsyncSubject<String> asyncSubject = AsyncSubject.create();
 sourceObservable.subscribe(
 data -> {
 asyncSubject.onNext(data);
 asyncSubject.onCompleted();
 },
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 asyncSubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 );
  • 44. Observable<String> sourceObservable = Observable.just("ONE");
 AsyncSubject<String> asyncSubject = AsyncSubject.create();
 sourceObservable.subscribe(
 data -> {
 asyncSubject.onNext(data);
 asyncSubject.onCompleted();
 },
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 asyncSubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 ); ONE
  • 45. Observable<String> sourceObservable = Observable.just("ONE");
 AsyncSubject<String> asyncSubject = AsyncSubject.create();
 sourceObservable.subscribe(
 data -> {
 asyncSubject.onNext(data);
 asyncSubject.onCompleted();
 },
 error -> Log.e(TAG, error.getMessage(), error)
 );
 
 asyncSubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 ); ONE
  • 48.
  • 50. Observable<String> sourceObservable = Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");
 ReplaySubject<String> replaySubject = ReplaySubject.create();
 sourceObservable.subscribe(
 replaySubject::onNext
 );
 
 replaySubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 );
  • 51. Observable<String> sourceObservable = Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");
 ReplaySubject<String> replaySubject = ReplaySubject.create();
 sourceObservable.subscribe(
 replaySubject::onNext
 );
 
 replaySubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 ); cache
  • 52. Observable<String> sourceObservable = Observable.just("ONE", "TWO", "THREE", "FOUR", "FIVE");
 ReplaySubject<String> replaySubject = ReplaySubject.create();
 sourceObservable.subscribe(
 replaySubject::onNext
 );
 
 replaySubject.subscribe(
 data -> Log.i(TAG, data),
 error -> Log.e(TAG, error.getMessage(), error)
 ); ONE, TWO, THREE, FOUR, FIVE
  • 56. public class RxEventBus {
 private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create());
 
 public void post(Object event) {
 bus.onNext(event);
 }
 
 public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {
 return bus.ofType(clazz).subscribe(onNext);
 }
 }
  • 57. public class RxEventBus {
 private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create());
 
 public void post(Object event) {
 bus.onNext(event);
 }
 
 public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {
 return bus.ofType(clazz).subscribe(onNext);
 }
 } Thread Safe Subject
  • 58. public class RxEventBus {
 private final Subject<Object, Object> bus = new SerializedSubject<>(PublishSubject.create());
 
 public void post(Object event) {
 bus.onNext(event);
 }
 
 public <T> Subscription subscribe(Class<T> clazz, Action1<T> onNext) {
 return bus.ofType(clazz).subscribe(onNext);
 }
 } bypass
  • 59. public class BusProvider {
 private static final RxEventBus eventBus = new RxEventBus();
 
 private BusProvider() {
 }
 
 public static RxEventBus getInstance() {
 return eventBus;
 }
 }
 Singleton
  • 60. public class ItemSelectEvent {
 private int position;
 
 public ItemSelectEvent(int position) {
 this.position = position;
 }
 
 public int getPosition() {
 return position;
 }
 }
 Simple Event
  • 61. public class Adapter extends RecyclerView.Adapter<ViewHolder> {
 private LayoutInflater layoutInflater;
 private List<String> texts;
 
 public Adapter(Context context) {
 layoutInflater = LayoutInflater.from(context);
 texts = new ArrayList<>();
 texts.add("あああああああああああ");
 ...
 }
 
 @Override
 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 View v = layoutInflater.inflate(R.layout.list_item, parent, false);
 ViewHolder viewHolder = new ViewHolder(v);
 viewHolder.itemView.setOnClickListener(view -> {
 int position = viewHolder.getAdapterPosition();
 if (position != RecyclerView.NO_POSITION) {
 BusProvider.getInstance().post(new ItemSelectEvent(position));
 }
 });
 return viewHolder;
 }
 
 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {
 holder.bind(texts.get(position));
 }
 
 @Override
 public int getItemCount() {
 return texts.size();
 }
 }
  • 62. public class Adapter extends RecyclerView.Adapter<ViewHolder> {
 private LayoutInflater layoutInflater;
 private List<String> texts;
 
 public Adapter(Context context) {
 layoutInflater = LayoutInflater.from(context);
 texts = new ArrayList<>();
 texts.add("あああああああああああ");
 ...
 }
 
 @Override
 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 View v = layoutInflater.inflate(R.layout.list_item, parent, false);
 ViewHolder viewHolder = new ViewHolder(v);
 viewHolder.itemView.setOnClickListener(view -> {
 int position = viewHolder.getAdapterPosition();
 if (position != RecyclerView.NO_POSITION) {
 BusProvider.getInstance().post(new ItemSelectEvent(position));
 }
 });
 return viewHolder;
 }
 
 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {
 holder.bind(texts.get(position));
 }
 
 @Override
 public int getItemCount() {
 return texts.size();
 }
 } ottoとほぼ同じ!
  • 63. public class MainActivity extends AppCompatActivity {
 private static final String TAG = MainActivity.class.getSimpleName();
 
 @Bind(R.id.recycler_view)
 RecyclerView recyclerView;
 
 private Subscription subscription;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ButterKnife.bind(this);
 
 recyclerView.setLayoutManager(new LinearLayoutManager(this));
 recyclerView.setHasFixedSize(true);
 recyclerView.setItemAnimator(new DefaultItemAnimator());
 recyclerView.setAdapter(new Adapter(this));
 }
 
 
 @Override
 protected void onResume() {
 super.onResume();
 subscription = BusProvider.getInstance().subscribe(
 ItemSelectEvent.class,
 e -> Toast.makeText(this, "position: " + e.getPosition(), Toast.LENGTH_SHORT).show()
 );
 }
 
 @Override
 protected void onPause() {
 subscription.unsubscribe();
 super.onPause();
 }
 }
  • 64. public class MainActivity extends AppCompatActivity {
 private static final String TAG = MainActivity.class.getSimpleName();
 
 @Bind(R.id.recycler_view)
 RecyclerView recyclerView;
 
 private Subscription subscription;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ButterKnife.bind(this);
 
 recyclerView.setLayoutManager(new LinearLayoutManager(this));
 recyclerView.setHasFixedSize(true);
 recyclerView.setItemAnimator(new DefaultItemAnimator());
 recyclerView.setAdapter(new Adapter(this));
 }
 
 
 @Override
 protected void onResume() {
 super.onResume();
 subscription = BusProvider.getInstance().subscribe(
 ItemSelectEvent.class,
 e -> Toast.makeText(this, "position: " + e.getPosition(), Toast.LENGTH_SHORT).show()
 );
 }
 
 @Override
 protected void onPause() {
 subscription.unsubscribe();
 super.onPause();
 }
 } ここもそっくり!