我们正在尝试使用 RxAndroid 库实现 Firebase 授权。
问题是所有自己的实现都以 instanceOf
结尾。我们正在努力摆脱它们。我觉得 ̶d̶i̶s̶t̶u̶r̶b̶a̶n̶c̶e̶ ̶i̶n̶ ̶t̶h̶e̶ ̶f̶o̶r̶c̶e̶我们正在以错误的方式使用 Rx 范式。最后,我们决定使用包装器库。
我们发现了 library已经为 Firebase 库实现了包装器。但实现也属于 instanceOf
例程。
这是使用 library 实现的示例:
public void resendVerificationCode(String phoneNumber) {
final Disposable disposable = RxPhoneAuthProvider.verifyPhoneNumber(
PhoneAuthProvider.getInstance(),
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
(Activity) mAuthenticationView,
forceResendingToken)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::phoneVerificationSuccess, this::phoneVerificationError);
mCompositeDisposable.add(disposable);
}
这是成功处理程序:
private void phoneVerificationSuccess(PhoneAuthEvent phoneAuthEvent){
if (phoneAuthEvent instanceof PhoneAuthCodeSentEvent) {
verificationId = ((PhoneAuthCodeSentEvent) phoneAuthEvent).verificationId();
forceResendingToken = ((PhoneAuthCodeSentEvent) phoneAuthEvent).forceResendingToken();
mAuthenticationView.showCodeSent();
}
if (phoneAuthEvent instanceof PhoneAuthVerificationCompleteEvent) {
PhoneAuthCredential credential = ((PhoneAuthVerificationCompleteEvent) phoneAuthEvent).credential();
mAuthenticationView.showVerifySuccess(credential);
signInWithPhoneAuthCredential(credential);
}
}
这是错误处理程序:
private void phoneVerificationError(Throwable throwable) {
if (throwable instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
mAuthenticationView.showInvalidPhoneNumber();
} else if (throwable instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
mAuthenticationView.showSMSQuotaExceeded();
}
mAuthenticationView.showVerificationFailedError(throwable.getMessage());
}
请告诉我们我们做错了什么?我觉得 instanceOf
味道不好,但我找不到任何其他方法来使用 Rx 实现 Firebase。
最佳答案
如果您的目标是不惜一切代价简单地消除 instanceof
,您可以执行类似的操作(通用形式)。
类层次结构:
class Thing {}
class FooThing extends Thing {}
class BarThing extends Thing {}
创建一个调度表,将扩展 Thing 的类映射到处理函数:
interface ThingHandler {
void handleThing(Thing thing);
}
Map<Class<? extends Thing>, ThingHandler> thingDispatch = new HashMap<>();
向其中添加知道如何处理每种类型的事物的处理程序:
thingDispatch.put(FooThing.class, new ThingHandler() {
@Override
public void handleThing(Thing thing) {
// assume Thing is a FooThing by casting it
FooThing fooThing = (FooThing) thing;
}
});
// etc
thingDispatch.put(BarThing.class, new ThingHandler() { ... });
现在当你有事情要处理时调用它:
Thing thing = ...;
thingDispatch.get(thing.getClass()).handleThing(thing);
恭喜,您已经消除了instanceof,但代价是增加了一堆额外的代码行!
在任何特定情况下,我都会保留对哪一个更好的判断。
关于java - 如何摆脱使用 RxJava 实现 Firebase 注册的 instanceOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827961/