Márió Posta
Márió Posta

Reputation: 173

Execute code just before onComplete() in RxJava 2?

I need to close socket connection in my observable before RxLifecycle dispose it. How can I do that?

Upvotes: 1

Views: 746

Answers (3)

Aks4125
Aks4125

Reputation: 5720

one can try this too in case if you're iterating objects using filter and map for combining result.

.doOnTerminate(() -> Log.d(LOGGER, "terminated"))

Upvotes: 1

paul
paul

Reputation: 13471

if you want to do an action after all, just before the subscriber unsubscribe from the observable you can use operator doOnUnsubscribe

@Test
public void testDoOnUnsubscribe() {
    Integer[] numbers = {0, 1, 2, 3, 4};
    Observable.from(numbers)
            .doOnUnsubscribe(() -> System.out.println("Last action must be done here"))
            .subscribe(number -> System.out.println("number:" + number),
                    System.out::println,
                    () -> System.out.println("End of pipeline"));
}

It should print in this order

number:0
number:1
number:2
number:3
number:4
End of pipeline
Last action must be done here

Upvotes: 2

triad
triad

Reputation: 21507

You could try using doFinally

Calls the specified action after this Observable signals onError or onCompleted or gets disposed by the downstream.

http://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html#doFinally-io.reactivex.functions.Action-

Upvotes: 1

Related Questions