Leonardo Deleon
Leonardo Deleon

Reputation: 2647

RxBus: send generic events

I have a generic Event class that I want to post on a PublishRelay that's acting as my bus.

I want to make my RxBus post events of generic type, but the bus itself is not generic. Can you give me ideas on what I need to change?

public class Event<T> {
  protected String name;
  protected Pair<String, T> event;

  public String getName() {
    return event.first;
  }

  public T getData() {
    return event.second; //cast to type
  }

  public Event(String name, T data) {
    event = Pair.create(name, data);
  }
}

@Singleton
public class RxBus {

    // I want to post Event<T>
  private final PublishRelay<Event<User>> busSubject = PublishRelay.create();

  public PublishRelay<Event<User>> bus() {
    return busSubject;
  }

  public void post(Event<User> event) {
    busSubject.accept(event);
  }
}

Upvotes: 0

Views: 582

Answers (1)

tynn
tynn

Reputation: 39843

If you want to use generic events, you could just use the ? wildcard for defining it. But then you have not information about the actual type of T in the subscriber. You'd have to handle this in a different way. Maybe filter or cast. Also it might not be good to make the PublishRelay accessible to the outside. Returning Observable would hide this implementation detail.

@Singleton
public class RxBus {

  private final PublishRelay<Event<?>> busSubject = PublishRelay.create();

  public Observable<Event<?>> bus() {
    return busSubject;
  }

  public void post(Event<?> event) {
    busSubject.accept(event);
  }
}

Upvotes: 1

Related Questions