本文介绍了RxJava而不是AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当人们试图说服我使用RxJava而不是Android的标准 AsyncTask 构造时,我遇到了几个例子。

I came across several instances when people were trying to persuade me into using RxJava instead of Android's standard AsyncTask construct.

在我看来,RxJava提供了更多功能,但在简单性方面与 AsyncTask 相比失去了。

In my opinion RxJava offers a lot more features but loses in simplicity against AsyncTask.

有没有RxJava甚至可以被认为是优越的用例(或者更普遍的RxJava)?

Are there any use cases that suit one approach better than the other or even more general can RxJava even be considered superior?

推荐答案

完全的力量在Java 8上使用它时,RxJava是可见的,最好是像Retrofit这样的库。它允许您轻松地将操作链接在一起,完全控制错误处理。例如,考虑以下代码 id :指定订单和apiClient的int:订单管理微服务的Retrofit客户端:

The full power of RxJava is visible when you use it on Java 8, preferably with a library like Retrofit. It allows you to trivially chain operations together, with full control of error handling. For example, consider the following code given id: an int that specifies the order and apiClient: a Retrofit client for the order management microservice:

apiClient
.getOrder(id)
.subscribeOn(Schedulers.io())
.flatMapIterable(Order::getLineItems)
.flatMap(lineItem ->
    apiClient.getProduct(lineItem.getProductId())
             .subscribeOn(Schedulers.io())
             .map(product -> product.getCurrentPrice() * lineItem.getCount()),
    5)
.reduce((a,b)->a+b)
.retryWhen((e, count) -> count<2 && (e instanceof RetrofitError))
.onErrorReturn(e -> -1)
.subscribe(System.out::println);

这将异步计算订单的总价,具有以下属性:

This will asynchronously calculate the total price of an order, with the following properties:


  • 在任何时候对飞行中的API提出的最多5个请求(并且您可以调整IO调度程序以对所有请求设置硬性上限,而不仅仅是单个可观察链)

  • 网络错误时最多重试2次

  • -1如果发生故障(反模式TBH,但这是一个其他讨论)

另外,IMO .subscribeOn(Schedulers.io())每次网络调用都应该是隐式的 - 您可以通过修改创建Retrofit客户端的方式来实现。对于11 + 2行代码来说还不错,即使它比Android-ish更加后端。

Also, IMO the .subscribeOn(Schedulers.io()) after each network call should be implicit - you can do that by modifying how you create the Retrofit client. Not bad for 11+2 lines of code, even if it's more backend-ish than Android-ish.

这篇关于RxJava而不是AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 10:14