我希望创建一个返回observable<Location>
它,我可以发送一个新的位置和用户获取最后一个加入任何后续值LocationHandler类。RX的Java 2,可观察到接受新值添加
我写这个类,它的工作原理,但我不知道这是否是这样做,因为我已经添加了一个回调,我闻到不好的正确方法。
感谢您的任何帮助。
public class LocationHandler {
private MessageHandler<Location> onNewItem;
private Observable<Location> locationObservable;
public LocationHandler(LocationInitializationBuilder locationInitBuilder) {
locationObservable = getHookedObservable()
.mergeWith(locationInitBuilder.build())
.replay(1).autoConnect();
}
private Observable<Location> getHookedObservable() {
return Observable.create(new ObservableOnSubscribe<Location>() {
@Override
public void subscribe(ObservableEmitter<Location> e) throws Exception {
onNewItem = location -> e.onNext(location);
}
});
}
public Observable<Location> getLocation(){
return locationObservable;
}
public void setLocation(Location address){ // <---------- add new values
if (onNewItem != null){
onNewItem.handleMessage(address);
} else {
throw new IllegalStateException("Cannot add an item to a never subscribed stream");
}
}
}
下面我用一个ReplaySubject修改了它@Blackbelt建议。
public class LocationHandler {
private ReplaySubject<Location> inputStream = ReplaySubject.create(1);
private Observable<Location> locationObservable;
public LocationHandler(LocationInitializationBuilder locationInitBuilder) {
locationObservable = locationInitBuilder.build()
.mergeWith(inputStream)
.replay(1).autoConnect();
}
public Observable<Location> getLocation(){
return locationObservable;
}
public void setLocation(Location address){
inputStream.onNext(address);
}
}
其实我不能,因为它是一个流通过我得到LocationInitializationBuilder.build使用行为。行为需要一个我无法在创作时提供的明确价值。 –
是的,我看到问题出在哪里。您的解决方案看起来合法 –
'BehaviourSubject'有一个静态方法'create',它创建一个空的'BehaviourSubject' – Blackbelt