mid*_*ght 2 android android-intent android-service rx-java greenrobot-eventbus
一个Activity包含一个Fragment又包含一个孩子Fragment,它要求一个孩子Service.该应用程序尝试实现dobjanschi休息架构.
当Service完成工作时,它必须传播操作结果.我尝试使用a PendingIntent但它似乎只被活动捕获,而我需要子片段才能得到通知.你能提出什么建议吗?活页夹?greenRobot Eventbus?RxJava(我在项目中已有)?
谢谢.
一个简单的方法是使用Singleton来包装同步的'PostSubject'
* Singleton
*
* to send an event use EventBusRx.getInstance().topic1.onNext("completed");
*/
public class EventBusRx {
private static EventBusRx ourInstance = new EventBusRx();
public static EventBusRx getInstance() {
return ourInstance;
}
private EventBusRx() {}
/**
* Use of multiple topics can be usefull
* SerializedSubject avoid concurrency issues
*/
public final Subject<String, String> topic1 = new SerializedSubject<>(PublishSubject.create());
public final Subject<Integer, Integer> topic2 = new SerializedSubject<>(PublishSubject.create());
}
Run Code Online (Sandbox Code Playgroud)
你可以从服务发送事件
EventBusRx.getInstance().topic1.onNext("completed");
Run Code Online (Sandbox Code Playgroud)
并以片段或随时响应事件
public class MyFragment extends Fragment {
// [...]
Subscription subscription_topic1;
@Override
public void onResume() {
super.onResume();
subscription_topic1 = EventBusRx.getInstance().topic2
.subscribeOn(AndroidSchedulers.mainThread()) // or on other sheduler
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
// update ui
}
});
}
@Override
public void onPause() {
// important to avoid memory leaks
subscription_topic1.unsubscribe();
super.onPause();
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记取消订阅订阅
这个想法类似于Roger'one使用单例,但强制执行ThreadSafety包装PublishSubject.
没有Observable.switchOnNext(主题)
greenRobot Eventbus和Otto很不错并具有相同的功能,但缺点是它们使连接更加烟雾(特别是EventBus).如果你已经使用rx我认为最好继续使用它
这是一篇关于使用RxJava实现事件总线主题的文章
这样做的经典方法是使用LocalBroadcastManager,但在我的意见中,他们很痛苦