我对RxJava和RxAndroid相当陌生,虽然有些工作正常,但我现在完全被我认为基本功能无法正常工作所困扰。
我对主题的订阅调用似乎永远不会运行,我无法弄清楚原因:
public class PairManager implements DiscoveryManagerListener {
private Subscription wifiAvailableSubscription;
private Subscription debugSubscription;
private DiscoveryManager discoveryManager;
private AsyncSubject<Map<String, ConnectableDevice>> availableDevices;
public PairManager(Context appContext) {
DiscoveryManager.init(appContext);
discoveryManager = DiscoveryManager.getInstance();
discoveryManager.addListener(this);
availableDevices = AsyncSubject.<Map<String, ConnectableDevice>> create();
//
// This subscription doesn't work
//
debugSubscription = availableDevices
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Map<String, ConnectableDevice>>() {
@Override
public void call(Map<String, ConnectableDevice> stringConnectableDeviceMap) {
//
// This code is never run !
//
Timber.d(">> Available devices changed %s", stringConnectableDeviceMap);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Timber.d("Subscription failed %s", throwable);
}
});
availableDevices.onNext(Collections.<String, ConnectableDevice>emptyMap());
wifiAvailableSubscription = ReactiveNetwork.observeNetworkConnectivity(appContext)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Connectivity>() {
@Override
public void call(Connectivity connectivity) {
if (connectivity.getState().equals(NetworkInfo.State.CONNECTED) && connectivity.getType() == ConnectivityManager.TYPE_WIFI) {
discoveryManager.start();
} else {
discoveryManager.stop();
availableDevices.onNext(Collections.<String, ConnectableDevice>emptyMap());
}
}
});
}
public AsyncSubject<Map<String, ConnectableDevice>> getAvailableDevices() {
return availableDevices;
}
@Override
public void onDeviceAdded(DiscoveryManager manager, ConnectableDevice device) {
Timber.d("onDeviceAdded %s", device);
availableDevices.onNext(manager.getAllDevices());
Timber.d("Sanity check %s", availableDevices.getValue());
}
// ...
}
有没有办法调试出错的地方?我尝试过创建基本的Observable.from
- 类型的调用并记录这些调用,并且按预期工作。 onDeviceAdded
中的完整性检查日志也会打印并指示availableDevices
实际上已按预期更新。我做错了什么?
答案 0 :(得分:0)
我发现了这个问题,我已经使用了AsyncSubjects,它们只有在完成时才会发出值,我期待BehaviorSubjects的功能。
答案 1 :(得分:0)
来自文件:
当连接性发生变化时,将通知用户。连通性可以改变其状态或类型。
你说:
我对主题
进行了订阅
主题不会返回最后一个值。我只会在调用onNext
时返回一个值。我认为连接性永远不会改变所以它永远不会发生。