SlideShare uma empresa Scribd logo
1 de 66
Baixar para ler 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、質疑応答

Mais conteúdo relacionado

Mais procurados

10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
Phúc Đỗ
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
Mayflower GmbH
 
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
julien.ponge
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 

Mais procurados (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
 

Semelhante a RxJava - Subject 入門

Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 

Semelhante 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
 

Mais de Fumihiko Shiroyama

Mais 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

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
VictoriaMetrics
 
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...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+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
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

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
 
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...
 
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...
 
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...
 
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 Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+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 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 Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%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
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

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