如何解决 RxJava onSuccess() 方法中意外的 return 值?

how to solve Unexpected return value in RxJava onSuccess() method?

我打算以此重构我的方法之一:

if (!isMobileBluetoothOn()) {
            sendError();
            return false;
        }

至此

getBluetoothState().subscribe(state->{
            if(!state.isEnabled()){
                sendError();
                return false;
            }
        });

但是我在 IDE "UnExpected return value" 中收到此错误,我怎样才能 return onSuccess 方法中的布尔值?

我建议您将此处的逻辑拆分为:

Observable<Boolean> isBluetoothEnabled = getBluetoothState()
    .map(state -> {state.isEnabled()})
    .replay(1)
    .refCount()
...
// use isBluetoothEnabled for something you need
...
isBluetoothEnabled
    .subscribe(isEnabled -> {
        if (!isEnabled) {
            sendError()
        }
    })

我真的不知道你的情况但是你说:

Actually I am calling this inside a method which's return type is boolean and I want to return that boolean from onSubscribed method

看来你要同步获取布尔值。对于响应式编程来说,这绝对是一种糟糕的做法,但无论如何你都可以将你 Observable 用作 BlockingObservable。代码如下所示:

val isEnabled = getBluetoothState().toBlocking().first().isEnabled()

您可以在此处阅读有关 BlockingObservable 的更多信息:http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html

尽量避免这种做法,但有时您必须使用它,而且可能是您的情况。

祝你好运!