2017-05-29 15 views
0

条件またはタイムアウトを待つ必要があります。私は次のアプローチを思いついたが、あまりにも多くのことが起こっている。どのように私はこれを圧縮することができます。Observable.intervalを使用してリモートデータまたはタイムアウトを待機する

import io.reactivex.Observable; 
import java.util.concurrent.TimeUnit; 
import io.reactivex.schedulers.Schedulers; 
import java.util.concurrent.atomic.AtomicBoolean; 
import java.util.concurrent.ThreadLocalRandom; 

public class Test{ 
    public static void main(String[] args)throws InterruptedException{ 
    AtomicBoolean toggle = new 
    java.util.concurrent.atomic.AtomicBoolean(true); 
    Observable.interval(0,50, TimeUnit.MILLISECONDS) 
      .takeWhile(l->l<(20000/50)) 
      .takeWhile(l-> toggle.get()) 
      .observeOn(Schedulers.io()) 
      .map(l->{ return (l>ThreadLocalRandom.current() 
          .nextInt(5, 20 + 1))?true:false;}) 
      // The above map will call a remote function to check for some condition 
      .observeOn(Schedulers.computation()) 
      .filter(exist->exist) 
      //.takeWhile(exist->!exist) 
      .map(l->{toggle.set(false);return l;}) 
      .map(l->{System.out.println("Called at "+l);return l;}) 
      .blockingSubscribe(); 
    } 
} 

答えて

1

ここはコードです。 firstElementを使用して最初の項目を取得できます。

import io.reactivex.Observable; 
import io.reactivex.schedulers.Schedulers; 

import java.util.concurrent.ThreadLocalRandom; 
import java.util.concurrent.TimeUnit; 

public class Q44234633 { 
    public static void main(String[] args) throws InterruptedException { 
    Observable.interval(50, TimeUnit.MILLISECONDS) 
     .takeWhile(l -> l < 400) 
     .observeOn(Schedulers.io()) 
     .filter(l -> isConditionTrue(l)) 
     .observeOn(Schedulers.computation()) 
     .firstElement() 
     .doOnSuccess(System.out::println) 
     .isEmpty() 
     .filter(empty -> empty) 
     .doOnSuccess(b -> System.out.println("TimeOut")) 
     .blockingGet(); 
    } 

    private static boolean isConditionTrue(long time) { 
    return time > ThreadLocalRandom.current().nextInt(5, 20 + 1); 
    } 
} 

また、2つのヒントがあります。

  1. あなたが実際に値をマッピングしていない場合は、doOnNextではなくmapを使用することができます。
  2. BooleanValue? true : falseBooleanValueと直接書き込むことができます。
+0

ありがとうございました。私は1を探していた。 –

+0

isOnSuccessが呼び出されるのは、isConditionTrueがtrueを返す場合です。これがタイムアウトしたかどうかはどうやって調べるのですか? –

+0

@JaganVeeraraghavanあなたは 'Maybe.isEmpty'を使うことができます。 –

関連する問題