说明
ReBus 是一个模仿 RxBus 写的,基于 reactor3 的事件总线
RxBus 一般是 Android 端使用的,
ReBus 一般是后端使用的
RxBus 参考链接: https://github.com/relengxing/RxBus
ReBus 源码链接: https://github.com/relengxing/ReBus
推荐直接看 RxBus 的解析,这边只贴代码,因为思想是一模一样的,只是底层的包不一样,封装完后用法也是一样的。
源码解析
ReBus 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| package com.relenxing.config; import com.relenxing.domain.Event; import reactor.core.publisher.Flux; import reactor.core.publisher.ReplayProcessor; public class ReBus {
private final ReplayProcessor<Event> bus;
private ReBus() { bus = ReplayProcessor.create(); }
public static ReBus getDefault() { return HelperHolder.instance; }
private static class HelperHolder { static final ReBus instance = new ReBus(); }
public void post(Event event){ bus.onNext(event); }
public Flux<Event> on(String type){ return bus.filter(e -> e.getEventName().equals(type)); } }
|
Event 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.relenxing.domain;
import java.io.Serializable;
public class Event<T> implements Serializable {
private static final long serialVersionUID = 1L;
private String eventName;
private T event;
public Event() { }
public Event(String eventName, T event) { this.eventName = eventName; this.event = event; }
public String getEventName() { return eventName; }
public void setEventName(String eventName) { this.eventName = eventName; }
public T getEvent() { return event; }
public void setEvent(T event) { this.event = event; } }
|
demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.relenxing; public class Main {
public static void main(String[] args) { ReBus.getDefault().post(new Event<>("123", "123")); ReBus.getDefault().post(new Event<>("456", "swdw")); ReBus.getDefault().post(new Event<>("123", "312")); ReBus.getDefault().post(new Event<>("456", "2f2")); ReBus.getDefault().post(new Event<>("123", "12f"));
ReBus.getDefault().on("123").map(Event::getEvent).subscribe(System.out::println); ReBus.getDefault().on("456").map(Event::getEvent).subscribe(System.out::println); } }
|