猿问

有条件地订阅 rxJava2 Observable

我有一个 rxJava2 Observable,我想有条件地订阅它。我将进行网络调用的场景,并且subscribe()仅在设备连接到网络时才调用。我想做如下的事情


     observable. 

     subsribeWhenConditionIsMet(


   if (connected to internet) {

      mPresentation.showNetworkError();

      return;

    }


   subscribe();

  }

)


关于如何做到这一点的任何建议?有没有更好的方法可用?


MYYA
浏览 173回答 2
2回答

慕雪6442864

目前在 RxJava2 中没有这样的方法可用。但是,如果您使用的是 kotlin,则可以使用扩展功能来完成。像下面这样声明它。fun <T> Observable<T>.subscribeIf(predicate: () -> Boolean) {&nbsp; &nbsp; if (predicate()) {&nbsp; &nbsp; &nbsp; &nbsp; subscribe()&nbsp; &nbsp; }}通话时:anyObservable()&nbsp; &nbsp; .subscribeIf { isConnectedToInternet() }额外的如果你想处理后备情况,你可以像下面这样编写你的扩展,并使后备 lambda 成为可选的,以便我们可以在不需要时省略它。fun <T> Observable<T>.subscribeIf(predicate: () -> Boolean, fallback: () -> Unit = {}) {&nbsp; &nbsp; if (predicate()) {&nbsp; &nbsp; &nbsp; &nbsp; subscribe()&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fallback()&nbsp; &nbsp; }}通话时:anyObservable()&nbsp; &nbsp; .subscribeIf(&nbsp; &nbsp; &nbsp; &nbsp; predicate = { isConnectedToInternet() },&nbsp; &nbsp; &nbsp; &nbsp; fallback = { showError() }&nbsp; &nbsp; )}注意:您也可以从 Java 调用它,请参阅此链接https://stackoverflow.com/a/28364983/3544839

慕桂英3389331

拥有互联网接入不仅仅是一个简单的条件,如果你仔细想想,它更像是一个布尔值流,有时是真的,有时是假的。您想要的是创建一个可在 Internet 连接可用时触发的 Observable。如果您使用的是 Android,则可以在广播接收器中使用 BehaviourSubjectpublic class NetworkChangeReceiver extends BroadcastReceiver {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onReceive(final Context context, final Intent intent) {&nbsp; &nbsp; &nbsp; &nbsp; final ConnectivityManager connMgr = (ConnectivityManager) context&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getSystemService(Context.CONNECTIVITY_SERVICE);&nbsp; &nbsp; &nbsp; &nbsp; final android.net.NetworkInfo wifi = connMgr&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getNetworkInfo(ConnectivityManager.TYPE_WIFI);&nbsp; &nbsp; &nbsp; &nbsp; final android.net.NetworkInfo mobile = connMgr&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);&nbsp; &nbsp; &nbsp; &nbsp; boolean hasInternet = wifi.isAvailable() || mobile.isAvailable()&nbsp; &nbsp; &nbsp; &nbsp; subject.onNext(hasInternet);&nbsp; &nbsp; }}您仍然需要以某种方式将主题传递给您的广播接收器,但这应该没什么大不了的。然后,为了仅在此主题返回 true 时订阅您的 observable,您可以这样做:&nbsp;subject&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(hasInternet ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasInternet // Don't continue if hasInternet is false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(o ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yourObservable // At this point, return the observable cause we have internet&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .subscribe() // subscribe
随时随地看视频慕课网APP

相关分类

Java
我要回答