Aldridge1991
Aldridge1991

Reputation: 1367

RXJava: Result of 'Single.subscribe()' is ignored

I'm learning the basics of RXJava. As you can see I have a small methods that justs checks if two integers are equal or not and returns the result in the form of a single

/**
 * 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));
}

I am getting a warning message showing:

Result of 'Single.subscribe()' is ignored

How could I get rid of this in a proper way?

Upvotes: 0

Views: 4170

Answers (2)

dthulke
dthulke

Reputation: 949

While PPartisans answer is correct regarding the warning you receive, the following might be cleaner to convert your observable to a single (there is no need for 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()
}

Upvotes: 0

PPartisan
PPartisan

Reputation: 8231

Single#subscribe returns a Disposable. Retaining a reference to this allows you to unsubscribe to the result of your Single at a later point.

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

Upvotes: 1

Related Questions