RXJava:“ Single.subscribe()”的结果被忽略

时间:2019-04-27 07:57:40

标签: android rx-java warnings

我正在学习RXJava的基础知识。如您所见,我有一个小的方法可以检查两个整数是否相等,并以单个

的形式返回结果
/**
 * This method checks if both online and offline shopping carts have the same number of items
 * @param numberOfItemsInLocalCart The number of items existing in the offline cart
 * @return true if items in both carts match, false otherwise
 */
public static Single<Boolean> run(int numberOfItemsInLocalCart)
{
    return Single.create(emitter ->
            _VolleyService.getInstance().getDataFuture(URLs.Home).subscribe(
                response ->
                {
                    ShoppingCart cart = HTMLParser.getItemsInShoppingCart(response);
                    if(cart.NumberOfElements == numberOfItemsInLocalCart)
                        emitter.onSuccess(true);
                    else
                        emitter.onSuccess(false);
                },
                    emitter::onError));
}

我收到一条警告消息,显示:

Result of 'Single.subscribe()' is ignored

我该如何以适当的方式摆脱这种情况?

2 个答案:

答案 0 :(得分:1)

Single#subscribe返回一个Disposable。保留对此的引用,可以使您以后退订Single的结果。

var disposable: Disposable? = run(20).subscribe()
//And later, if you're no longer interested in the result of your Single...
disposable?.dispose()

答案 1 :(得分:0)

虽然PPartisans对收到的警告的回答是正确的,但以下方法可能更干净一些,可以将您的可观察对象转换为单个对象(不需要Single.create):

public static Single<Boolean> run(int numberOfItemsInLocalCart) {
    return _VolleyService.getInstance().getDataFuture(URLs.Home)
            .map(response -> {
                    ShoppingCart cart = HTMLParser.getItemsInShoppingCart(response);
                    return cart.NumberOfElements == numberOfItemsInLocalCart
            }.singleOrError()
}