content: /**
   * Copyright (c) 2016-present, RxJava Contributors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
   * compliance with the License. You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software distributed under the License is
   * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
   * the License for the specific language governing permissions and limitations under the License.
   */
  
  package io.reactivex.interop.internal.operators;
  
  import static io.reactivex.interop.RxJava3Interop.*;
  import static org.junit.Assert.*;
  
  import java.util.*;
  import java.util.concurrent.*;
  
  import org.junit.Test;
  import org.reactivestreams.Subscriber;
  
  import io.reactivex.common.*;
  import io.reactivex.common.exceptions.*;
  import io.reactivex.common.functions.Function;
  import io.reactivex.common.internal.functions.Functions;
  import io.reactivex.flowable.Flowable;
  import io.reactivex.interop.TestHelper;
  import io.reactivex.flowable.internal.subscriptions.BooleanSubscription;
  import io.reactivex.flowable.processors.PublishProcessor;
  import io.reactivex.flowable.subscribers.TestSubscriber;
  import io.reactivex.observable.*;
  
  public class FlowableFlatMapMaybeTest {
  
      @Test
      public void normal() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          })
          .test()
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void normalEmpty() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.empty();
              }
          })
          .test()
          .assertResult();
      }
  
      @Test
      public void normalDelayError() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          }, true, Integer.MAX_VALUE)
          .test()
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void normalAsync() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v).subscribeOn(Schedulers.computation());
              }
          })
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertSubscribed()
          .assertValueSet(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
          .assertNoErrors()
          .assertComplete();
      }
  
      @Test
      public void normalAsyncMaxConcurrency() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v).subscribeOn(Schedulers.computation());
              }
          }, false, 3)
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertSubscribed()
          .assertValueSet(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
          .assertNoErrors()
          .assertComplete();
       }
  
      @Test
      public void normalAsyncMaxConcurrency1() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v).subscribeOn(Schedulers.computation());
              }
          }, false, 1)
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void mapperThrowsFlowable() {
          PublishProcessor<Integer> ps = PublishProcessor.create();
  
          TestSubscriber<Integer> to =
          flatMapMaybe(ps, new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  throw new TestException();
              }
          })
          .test();
  
          assertTrue(ps.hasSubscribers());
  
          ps.onNext(1);
  
          to.assertFailure(TestException.class);
  
          assertFalse(ps.hasSubscribers());
      }
  
      @Test
      public void mapperReturnsNullFlowable() {
          PublishProcessor<Integer> ps = PublishProcessor.create();
  
          TestSubscriber<Integer> to =
          flatMapMaybe(ps, new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return null;
              }
          })
          .test();
  
          assertTrue(ps.hasSubscribers());
  
          ps.onNext(1);
  
          to.assertFailure(NullPointerException.class);
  
          assertFalse(ps.hasSubscribers());
      }
  
      @Test
      public void normalDelayErrorAll() {
          TestSubscriber<Integer> to =
          flatMapMaybe(Flowable.range(1, 10).concatWith(Flowable.<Integer>error(new TestException())),
          new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.error(new TestException());
              }
          }, true, Integer.MAX_VALUE)
          .test()
          .assertFailure(CompositeException.class);
  
          List<Throwable> errors = TestCommonHelper.compositeList(to.errors().get(0));
  
          for (int i = 0; i < 11; i++) {
              TestCommonHelper.assertError(errors, i, TestException.class);
          }
      }
  
      @Test
      public void normalBackpressured() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          })
          .rebatchRequests(1)
          .test()
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void normalMaxConcurrent1Backpressured() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          }, false, 1)
          .rebatchRequests(1)
          .test()
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void normalMaxConcurrent2Backpressured() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          }, false, 2)
          .rebatchRequests(1)
          .test()
          .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
      }
  
      @Test
      public void takeAsync() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v).subscribeOn(Schedulers.computation());
              }
          })
          .take(2)
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertSubscribed()
          .assertValueCount(2)
          .assertValueSet(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
          .assertNoErrors()
          .assertComplete();
      }
  
      @Test
      public void take() {
          flatMapMaybe(Flowable.range(1, 10), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(v);
              }
          })
          .take(2)
          .test()
          .assertResult(1, 2);
      }
  
      @Test
      public void middleError() {
          flatMapMaybe(Flowable.fromArray(new String[]{"1","a","2"}), new Function<String, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(final String s) throws NumberFormatException {
                  //return Maybe.just(Integer.valueOf(s)); //This works
                  return Maybe.fromCallable(new Callable<Integer>() {
                      @Override
                      public Integer call() throws NumberFormatException {
                          return Integer.valueOf(s);
                      }
                  });
              }
          })
          .test()
          .assertFailure(NumberFormatException.class, 1);
      }
  
      @Test
      public void disposed() {
          TestHelper.checkDisposed(
                  flatMapMaybe(PublishProcessor.<Integer>create(), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.<Integer>empty();
              }
          }));
      }
  
      @Test
      public void asyncFlatten() {
          flatMapMaybe(Flowable.range(1, 1000), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.just(1).subscribeOn(Schedulers.computation());
              }
          })
          .take(500)
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertSubscribed()
          .assertValueCount(500)
          .assertNoErrors()
          .assertComplete();
      }
  
      @Test
      public void asyncFlattenNone() {
          flatMapMaybe(Flowable.range(1, 1000), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  return Maybe.<Integer>empty().subscribeOn(Schedulers.computation());
              }
          })
          .take(500)
          .test()
          .awaitDone(5, TimeUnit.SECONDS)
          .assertResult();
      }
  
      @Test
      public void successError() {
          final PublishProcessor<Integer> ps = PublishProcessor.create();
  
          TestSubscriber<Integer> to =
          flatMapMaybe(Flowable.range(1, 2), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  if (v == 2) {
                      return singleElement(ps);
                  }
                  return Maybe.error(new TestException());
              }
          }, true, Integer.MAX_VALUE)
          .test();
  
          ps.onNext(1);
          ps.onComplete();
  
          to
          .assertFailure(TestException.class, 1);
      }
  
      @Test
      public void completeError() {
          final PublishProcessor<Integer> ps = PublishProcessor.create();
  
          TestSubscriber<Integer> to =
          flatMapMaybe(Flowable.range(1, 2), new Function<Integer, MaybeSource<Integer>>() {
              @Override
              public MaybeSource<Integer> apply(Integer v) throws Exception {
                  if (v == 2) {
                      return singleElement(ps);
                  }
                  return Maybe.error(new TestException());
              }
          }, true, Integer.MAX_VALUE)
          .test();
  
          ps.onComplete();
  
          to
          .assertFailure(TestException.class);
      }
  
      @Test
      public void doubleOnSubscribe() {
          TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Integer>>() {
              @Override
              public Flowable<Integer> apply(Flowable<Object> f) throws Exception {
                  return flatMapMaybe(f, Functions.justFunction(Maybe.just(2)));
              }
          });
      }
  
      @Test
      public void badSource() {
          List<Throwable> errors = TestCommonHelper.trackPluginErrors();
          try {
              flatMapMaybe(new Flowable<Integer>() {
                  @Override
                  protected void subscribeActual(Subscriber<? super Integer> observer) {
                      observer.onSubscribe(new BooleanSubscription());
                      observer.onError(new TestException("First"));
                      observer.onError(new TestException("Second"));
                  }
              }, Functions.justFunction(Maybe.just(2)))
              .test()
              .assertFailureAndMessage(TestException.class, "First");
  
              TestCommonHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
          } finally {
              RxJavaCommonPlugins.reset();
          }
      }
  
      @Test
      public void badInnerSource() {
          List<Throwable> errors = TestCommonHelper.trackPluginErrors();
          try {
              flatMapMaybe(Flowable.just(1), Functions.justFunction(new Maybe<Integer>() {
                  @Override
                  protected void subscribeActual(MaybeObserver<? super Integer> observer) {
                      observer.onSubscribe(Disposables.empty());
                      observer.onError(new TestException("First"));
                      observer.onError(new TestException("Second"));
                  }
              }))
              .test()
              .assertFailureAndMessage(TestException.class, "First");
  
              TestCommonHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
          } finally {
              RxJavaCommonPlugins.reset();
          }
      }
  
      @Test
      public void emissionQueueTrigger() {
          final PublishProcessor<Integer> ps1 = PublishProcessor.create();
          final PublishProcessor<Integer> ps2 = PublishProcessor.create();
  
          TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
              @Override
              public void onNext(Integer t) {
                  super.onNext(t);
                  if (t == 1) {
                      ps2.onNext(2);
                      ps2.onComplete();
                  }
              }
          };
  
          flatMapMaybe(Flowable.just(ps1, ps2), new Function<PublishProcessor<Integer>, MaybeSource<Integer>>() {
                      @Override
                      public MaybeSource<Integer> apply(PublishProcessor<Integer> v) throws Exception {
                          return singleElement(v);
                      }
                  })
          .subscribe(to);
  
          ps1.onNext(1);
          ps1.onComplete();
  
          to.assertResult(1, 2);
      }
  
      @Test
      public void emissionQueueTrigger2() {
          final PublishProcessor<Integer> ps1 = PublishProcessor.create();
          final PublishProcessor<Integer> ps2 = PublishProcessor.create();
          final PublishProcessor<Integer> ps3 = PublishProcessor.create();
  
          TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
              @Override
              public void onNext(Integer t) {
                  super.onNext(t);
                  if (t == 1) {
                      ps2.onNext(2);
                      ps2.onComplete();
                  }
              }
          };
  
          flatMapMaybe(Flowable.just(ps1, ps2, ps3), new Function<PublishProcessor<Integer>, MaybeSource<Integer>>() {
                      @Override
                      public MaybeSource<Integer> apply(PublishProcessor<Integer> v) throws Exception {
                          return singleElement(v);
                      }
                  })
          .subscribe(to);
  
          ps1.onNext(1);
          ps1.onComplete();
  
          ps3.onComplete();
  
          to.assertResult(1, 2);
      }
  
      @Test
      public void disposeInner() {
          final TestSubscriber<Object> to = new TestSubscriber<Object>();
  
          flatMapMaybe(Flowable.just(1), new Function<Integer, MaybeSource<Object>>() {
              @Override
              public MaybeSource<Object> apply(Integer v) throws Exception {
                  return new Maybe<Object>() {
                      @Override
                      protected void subscribeActual(MaybeObserver<? super Object> observer) {
                          observer.onSubscribe(Disposables.empty());
  
                          assertFalse(((Disposable)observer).isDisposed());
  
                          to.dispose();
  
                          assertTrue(((Disposable)observer).isDisposed());
                      }
                  };
              }
          })
          .subscribe(to);
  
          to
          .assertEmpty();
      }
  
      @Test
      public void innerSuccessCompletesAfterMain() {
          PublishProcessor<Integer> ps = PublishProcessor.create();
  
          TestSubscriber<Integer> to =
          flatMapMaybe(Flowable.just(1), Functions.justFunction(singleElement(ps)))
          .test();
  
          ps.onNext(2);
          ps.onComplete();
  
          to
          .assertResult(2);
      }
  
      @Test
      public void backpressure() {
          TestSubscriber<Integer> ts =
          flatMapMaybe(Flowable.just(1), Functions.justFunction(Maybe.just(2)))
          .test(0L)
          .assertEmpty();
  
          ts.request(1);
          ts.assertResult(2);
      }
  
      @Test
      public void error() {
          flatMapMaybe(Flowable.just(1), Functions.justFunction(Maybe.<Integer>error(new TestException())))
          .test(0L)
          .assertFailure(TestException.class);
      }
  
      @Test
      public void errorDelayed() {
          flatMapMaybe(Flowable.just(1), Functions.justFunction(Maybe.<Integer>error(new TestException())), true, 16)
          .test(0L)
          .assertFailure(TestException.class);
      }
  
      @Test
      public void requestCancelRace() {
          for (int i = 0; i < 500; i++) {
              final TestSubscriber<Integer> to =
              flatMapMaybe(Flowable.just(1).concatWith(Flowable.<Integer>never()), Functions.justFunction(Maybe.just(2))).test(0);
  
              Runnable r1 = new Runnable() {
                  @Override
                  public void run() {
                      to.request(1);
                  }
              };
              Runnable r2 = new Runnable() {
                  @Override
                  public void run() {
                      to.cancel();
                  }
              };
  
              TestCommonHelper.race(r1, r2);
          }
      }
  }
  