我试图从按钮流中获取一个observable然后使用另一个obintable来改造以请求端点,但它只运行一次!当我再次点击时,不要通过平面地图方法。
这是一个奇怪的原因,当flatmap返回其他可观察的时候,它运行正常,但是通过改造它只会运行一次。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var retrofit:Retrofit = Retrofit.Builder()
.baseUrl("<SERVER_IP>")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
var testService:TestService = retrofit.create(TestService::class.java)
var buttonObservable:Observable<Void> = RxView.clicks(btnRequest)
buttonObservable
.observeOn(Schedulers.newThread())
.subscribeOn(AndroidSchedulers.mainThread())
.flatMap {
Log.i("debug", "run flatmap")
var request:Request = Request()
request.accessToken = "<acess_token>"
testService.test(request)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user ->
Log.i("debug", "user ")
},
{ err ->
Log.d("debug", "err: ${err.message}")
})
}
测试界面:
interface TestService {
@POST("protected")
fun test(@Body request: Request) : Observable<User>
}
请求类:
class Request {
var accessToken:String = ""
}
提前致谢!!!!
编辑: 最后,发生的事情是onError是触发器,它会停止流。
以下代码解决了这个问题:
buttonObservable
.observeOn(Schedulers.newThread())
.subscribeOn(AndroidSchedulers.mainThread())
.flatMap {
try {
Log.i("debug", "run flatmap")
var blaService = retrofit.create(TestService::class.java)
var request: Request = Request()
blaService.test(request)
} catch(t:Throwable) {
Observable.empty<Void>()
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ user ->
Log.i("debug", "user ")
},
{ err ->
Log.d("debug", "err: ${err.message}")
}, {
Log.i("debug", "onComplete")
})
但这不是更好的方法,在点击onError或onComplete之后有正确的方法来继续流吗?