2017-01-27 43 views
1

我對RxJava和RxAndroid相當新,雖然有些事情可以工作,但我現在完全被我看到的基本功能無法正常工作。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

我發現了這個問題,我使用了AsyncSubjects,它們在完成時只發出值,我期待BehaviorSubjects的功能。

0

從doccumentation:

連接變化時,用戶將會收到通知。連接可以改變其狀態或類型。

你說:

我有一個訂閱調用一個主題

主題將不會返回TE最後一個值。我只會在調用onNext時返回一個值。我認爲連接不會改變,所以它永遠不會啓動。