问题描述
我开始学习RxJava,到目前为止我喜欢它.我有一个片段,它与单击按钮时的活动进行通信(用新片段替换当前片段).Google建议使用界面来使片段与活动进行交流,但是它太冗长,我尝试使用广播接收器虽然可以正常工作,但是有缺点.
I'm start learning RxJava and I like it so far. I have a fragment that communicate with an activity on button click (to replace the current fragment with a new fragment). Google recommends interface for fragments to communicate up to the activity but it's too verbose, I tried to use broadcast receiver which works generally but it had drawbacks.
由于我正在学习RxJava,所以我想知道从片段到活动(或片段到片段)进行通信是否是一个好选择?如果是这样,那么使用RxJava进行此类通信的最佳方法是什么?我是否需要像这样一个,如果是这种情况,我应该制作一个总线实例并在全局范围内使用它(带有主题)吗?
Since I'm learning RxJava I wonder if it's a good option to communicate from fragments to activities (or fragment to fragment)?. If so, whats the best way to use RxJava for this type of communication?. Do I need to make event bus like this one and if that's the case should I make a single instance of the bus and use it globally (with subjects)?
推荐答案
是的,在您学习了如何做之后,这真是太了不起了.考虑以下单例类:
Yes and it's pretty amazing after you learn how to do it. Consider the following singleton class:
public class UsernameModel {
private static UsernameModel instance;
private PublishSubject<String> subject = PublishSubject.create();
public static UsernameModel instanceOf() {
if (instance == null) {
instance = new UsernameModel();
}
return instance;
}
/**
* Pass a String down to event listeners.
*/
public void setString(String string) {
subject.onNext(string);
}
/**
* Subscribe to this Observable. On event, do something e.g. replace a fragment
*/
public Observable<String> getStringObservable() {
return subject;
}
}
在您的活动"中准备接收事件(例如,将其放在onCreate中):
In your Activity be ready to receive events (e.g. have it in the onCreate):
UsernameModel usernameModel = UsernameModel.instanceOf();
//be sure to unsubscribe somewhere when activity is "dying" e.g. onDestroy
subscription = usernameModel.getStringObservable()
.subscribe(s -> {
// Do on new string event e.g. replace fragment here
}, throwable -> {
// Normally no error will happen here based on this example.
});
在您的Fragment中,发生事件时将其传递:
In you Fragment pass down the event when it occurs:
UsernameModel.instanceOf().setString("Nick");
您的活动将会有所作为.
Your activity then will do something.
提示1:使用所需的任何对象类型更改字符串.
Tip 1: Change the String with any object type you like.
提示2:如果您有依赖项注入,它也很好用.
Tip 2: It works also great if you have Dependency injection.
更新:我写了更长的文章
这篇关于RxJava作为事件总线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!