我是 rxjava2 的新手,我想用它来配合我现有的代码来解决忽略回调 hell 的问题。主要任务类似于下面的代码:
SomeTask.execute(new Callback() {
@Override
public void onSuccess(Data data) {
// I want to add data into observable stream here
}
@Override
public void onFailure(String errorMessage) {
// I want to perform some different operations
// to errorMessage rather than the data in `onSuccess` callback.
// I am not sure if I should split the data stream into two different Observable streams
// and use different Observers to accomplish different logic.
// and I don't know how to do it.
}
}
我在 Google 和 Stackoverflow 上做了一些挖掘,但仍然没有找到创建可观察对象来实现这两个目标的完美解决方案。
- 包装现有的回调函数。
- 以不同的逻辑处理不同的回调数据。
任何建议都会有很大的帮助。
最佳答案
看看这个article .它会帮助你。
这是您的问题的可能解决方案 (Kotlin):
Observable.create<Data> { emitter ->
SomeTask.execute(object: Callback() {
override void onSuccess(data: Data) {
emitter.onNext(data)
emitter.onComplete()
}
override void onFailure(errorMessage: String) {
// Here you must pass the Exception, not the message
emitter.onError(exception)
}
}
}
Do not forget to subscribe and dispose the Observable.
您还必须考虑使用 Single、Maybe 或任何其他 Observable 类型。
关于android - rxjava2 从现有回调函数创建 Observable 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709646/