Kaloyan Roussev
Kaloyan Roussev

Reputation: 14711

How to stop an RxJava observable from emitting items. Tried to unsubscribe but it kept going

In my code I create an observable and keep a reference to the subscription object. When I start the app it prints all the numbers from 1 to 1000000 If I minimize the activity, I ubsubscribe from the subscription in onPause However, the LogCat keeps printing numbers. How do I stop it from doing so?

public class MainActivity extends AppCompatActivity {

    private Subscription printingNumbers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        printingNumbers = Observable
                          .range(1, 500000)
                          .map(i -> i*2)
                          .subscribe(i -> System.out.println(i));
    }

    @Override
    protected void onPause() {
        super.onPause();
        printingNumbers.unsubscribe();
    }

}

Upvotes: 0

Views: 570

Answers (1)

X3Btel
X3Btel

Reputation: 1428

Range returns all the values at once but takes time on the Log to visualize it. Interval will return values at given time, that way you can test your unsubscribe.

PS: I think you can combine range and interval to emiits value up to a limit at given interval, but not sure as im just learning RX

Upvotes: 1

Related Questions