【问题标题】:Can I delay the onSuccess method in RxJava?Can I delay the onSuccess method in RxJava?
【发布时间】:2022-12-26 16:01:17
【问题描述】:

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?

【问题讨论】:

    标签: java android retrofit retrofit2 rx-java


    【解决方案1】:

    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 -> { });
    

    【讨论】:

      【解决方案2】:

      Try it.

      private fun setupSplashTimer() {
          loadApiFromServer()
          Single.timer(8, TimeUnit.SECONDS)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .doAfterTerminate {
                  // this method will be called after 8 seconds
                  // Next screen
              }
              .subscribe({
                  // Call success
              }, {
                  // Call error
              })
      }
      
      private fun loadApiFromServer() {
          // Call api here
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-27
        • 2022-12-01
        • 2022-12-02
        • 2022-12-19
        • 1970-01-01
        • 2022-12-26
        • 2022-11-20
        • 2022-12-01
        • 2022-12-27
        相关资源
        最近更新 更多