SlideShare una empresa de Scribd logo
1 de 66
Descargar para leer sin conexión
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、質疑応答

Más contenido relacionado

La actualidad más candente

連邦の白いヤツ 「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
 

La actualidad más candente (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 a 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 a 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
 

Más de 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
 

Más de 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
 

Último

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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%+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
 
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
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
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
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 

Último (20)

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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+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...
 
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-...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
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 🔝✔️✔️
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

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();
 }
 } ここもそっくり!