如何在Android中使用RxJava在活动之间传递数据? [英] How pass data between activities using RxJava in android?
问题描述
我需要在两个活动 MainActivity
和 ChildActivity
之间传递一些数据.单击 MainActivity
上的按钮,应打开 ChildActivity
并发送事件和数据.我有单身人士:
Subject<对象,对象>主题=新的SerializedSubject<>(PublishSubject.create());
和 MainActivity
中,我具有以下按钮单击处理程序:
public void onClick(){startActivity(new Intent(MainActivity.this,ChildActivity.class));subject.onNext(new SomeEvent(data));}
和 ChildActivity
中的事件侦听器订阅:
@Override受保护的void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);addEventListeners();}私人无效addEventListeners(){subject.ofType(SomeEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(事件->{loadData(event.getData());});}
当我在开始活动后发送事件并在 ChildActivity
onCreate
中调用 addEventListeners
时,仍未订阅此事件,并且 loadData()
不被调用.
使用RxJava在活动之间传递数据的正确方法是什么(如果可能)?
原因:
问题是您正在使用 PublishSubject
.根据 PublishSubject
的文档,在订阅时会发出源Observable的所有后续项.因此,根据您的情况,它只有在被订阅时才会发出事件.
解决您的问题
使用 BehaviorSubject
代替使用 PublishSubject
,它会在观察者订阅时发出最近可发射的项目以及源Observable的所有后续项目.
浏览以下链接以获取更多详细信息.>
I need to pass some data between two activities MainActivity
and ChildActivity
. Button click on MainActivity
should open ChildActivity
and send event with data. I have singleton:
Subject<Object, Object> subject = new SerializedSubject<>(PublishSubject.create());
and in MainActivity
I have the following button click handler:
public void onClick(){
startActivity(new Intent(MainActivity.this, ChildActivity.class));
subject.onNext(new SomeEvent(data));
}
and event listener subscription in ChildActivity
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addEventListeners();
}
private void addEventListeners() {
subject.ofType(SomeEvent.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()).subscribe(
event -> {
loadData(event.getData());
});
}
When I send event after starting activity and call addEventListeners
in ChildActivity
onCreate
is still not subscribed to this event and loadData()
is not called.
What is proper way to pass data between activities using RxJava (if it's possible)?
Reason:
Problem is that you are using PublishSubject
. As per documentation of PublishSubject
emits all the subsequent items of the source Observable at the time of the subscription. So in your case it will emit event only if it is subscribed.
Fix for your problem
Instead of using PublishSubject
use BehaviorSubject
which emits the most recently emitted item and all the subsequent items of the source Observable when a observer subscribe to it.
Browse following link for more details.
这篇关于如何在Android中使用RxJava在活动之间传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!