Skip to content
Advertisement

Can I delay the onSuccess method in RxJava?

I have SplashScreenFragment and inside this fragment, I’ll load the data from the server using Retrofit with RxJava, Getting data from the server will take between 1 second to 25 seconds.

The SplashScreenFragment must show to the user for at least 8 seconds.

When I get the data from the server, The onSuccess method will be called and inside this the onSuccess method I’ll navigate the user to the HomeFragment

Let’s take an example to understand what I want exactly:

First Scenario: When I open the app, The SplashScreenFragment will be launched and it will get the data from the server, Let’s suppose it took 1 second to get the data from the server, In this situation, It must not call with the onSuccess method, Should wait 7 seconds and after that, It must call the onSuccess method

Second Scenario: When I open the app, The SplashScreenFragment will be launched and it will get the data from the server, Let’s suppose it took 3 seconds to get the data from the server, In this situation, It must not call with the onSuccess method, Should wait 5 seconds and after that, It must call the onSuccess method

Third Scenario: When I open the app, The SplashScreenFragment will be launched and it will get the data from the server, Let’s suppose it took 12 seconds to get the data from the server, In this situation, Must call with the onSuccess method directly without waiting.

I can do that, But without RxJava, I want to know is there any method in RxJava to delay the onSuccess method depending on the conditions above?

Advertisement

Answer

Zip it with an 8 second timer:

Single<Data> datasource = ...

datasource.zipWith(Single.timer(8, TimeUnit.SECONDS), (a, b) -> a)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(data -> { }, error -> { });
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement