Search in sources :

Example 26 with Supplier

use of io.reactivex.rxjava3.functions.Supplier in project radixdlt by radixdlt.

the class RecoveryLivenessTest method setup.

@Before
public void setup() {
    this.messageMutator = MessageMutator.nothing();
    this.network = new DeterministicNetwork(nodeKeys.stream().map(k -> BFTNode.create(k.getPublicKey())).toList(), MessageSelector.firstSelector(), this::mutate);
    var allNodes = nodeKeys.stream().map(k -> BFTNode.create(k.getPublicKey())).toList();
    this.nodeCreators = nodeKeys.stream().<Supplier<Injector>>map(k -> () -> createRunner(k, allNodes)).toList();
    for (Supplier<Injector> nodeCreator : nodeCreators) {
        this.nodes.add(nodeCreator.get());
    }
    this.nodes.forEach(i -> i.getInstance(DeterministicProcessor.class).start());
}
Also used : ControlledMessage(com.radixdlt.environment.deterministic.network.ControlledMessage) RadixEngineForksLatestOnlyModule(com.radixdlt.statecomputer.forks.RadixEngineForksLatestOnlyModule) Timed(io.reactivex.rxjava3.schedulers.Timed) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) PersistedNodeForTestingModule(com.radixdlt.PersistedNodeForTestingModule) EpochView(com.radixdlt.consensus.epoch.EpochView) FeeTable(com.radixdlt.application.system.FeeTable) After(org.junit.After) MSG(com.radixdlt.constraintmachine.REInstruction.REMicroOp.MSG) View(com.radixdlt.consensus.bft.View) Parameterized(org.junit.runners.Parameterized) ThreadContext(org.apache.logging.log4j.ThreadContext) DatabaseEnvironment(com.radixdlt.store.DatabaseEnvironment) PersistentSafetyStateStore(com.radixdlt.consensus.safety.PersistentSafetyStateStore) Collection(java.util.Collection) Set(java.util.Set) LastEventsModule(com.radixdlt.environment.deterministic.LastEventsModule) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) KeyComparator(com.radixdlt.utils.KeyComparator) Optional(java.util.Optional) Amount(com.radixdlt.application.tokens.Amount) Pattern(java.util.regex.Pattern) MainnetForkConfigsModule(com.radixdlt.statecomputer.forks.MainnetForkConfigsModule) TypeLiteral(com.google.inject.TypeLiteral) SyncCheckTrigger(com.radixdlt.sync.messages.local.SyncCheckTrigger) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) OptionalInt(java.util.OptionalInt) Supplier(java.util.function.Supplier) DeterministicNetwork(com.radixdlt.environment.deterministic.network.DeterministicNetwork) EpochViewUpdate(com.radixdlt.consensus.epoch.EpochViewUpdate) ArrayList(java.util.ArrayList) MockedGenesisModule(com.radixdlt.statecomputer.checkpoint.MockedGenesisModule) ClassToInstanceMap(com.google.common.collect.ClassToInstanceMap) ImmutableList(com.google.common.collect.ImmutableList) DatabaseLocation(com.radixdlt.store.DatabaseLocation) MessageSelector(com.radixdlt.environment.deterministic.network.MessageSelector) MempoolConfig(com.radixdlt.mempool.MempoolConfig) RERulesConfig(com.radixdlt.statecomputer.forks.RERulesConfig) MessageQueue(com.radixdlt.environment.deterministic.network.MessageQueue) BerkeleyLedgerEntryStore(com.radixdlt.store.berkeley.BerkeleyLedgerEntryStore) Before(org.junit.Before) EventDispatcher(com.radixdlt.environment.EventDispatcher) Environment(com.radixdlt.environment.Environment) Test(org.junit.Test) DeterministicProcessor(com.radixdlt.environment.deterministic.DeterministicProcessor) ForksModule(com.radixdlt.statecomputer.forks.ForksModule) Injector(com.google.inject.Injector) Provides(com.google.inject.Provides) ECKeyPair(com.radixdlt.crypto.ECKeyPair) Rule(org.junit.Rule) Self(com.radixdlt.consensus.bft.Self) Guice(com.google.inject.Guice) BFTNode(com.radixdlt.consensus.bft.BFTNode) MessageMutator(com.radixdlt.environment.deterministic.network.MessageMutator) PeersView(com.radixdlt.network.p2p.PeersView) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) TemporaryFolder(org.junit.rules.TemporaryFolder) AbstractModule(com.google.inject.AbstractModule) DeterministicNetwork(com.radixdlt.environment.deterministic.network.DeterministicNetwork) Injector(com.google.inject.Injector) Supplier(java.util.function.Supplier) Before(org.junit.Before)

Example 27 with Supplier

use of io.reactivex.rxjava3.functions.Supplier in project xxf_android by NBXXF.

the class StringFileService method writeFileString.

/**
 * 写
 *
 * @param file
 * @param content
 * @param append
 * @return
 */
default Observable<File> writeFileString(File file, String content, boolean append) {
    return Observable.defer(new Supplier<ObservableSource<? extends File>>() {

        @Override
        public ObservableSource<? extends File> get() throws Throwable {
            FileUtils.createOrExistsFile(file);
            try (FileWriter fw = new FileWriter(file, append)) {
                fw.write(content);
                fw.flush();
            }
            return Observable.just(file);
        }
    }).subscribeOn(Schedulers.io());
}
Also used : FileWriter(java.io.FileWriter) Supplier(io.reactivex.rxjava3.functions.Supplier)

Example 28 with Supplier

use of io.reactivex.rxjava3.functions.Supplier in project xxf_android by NBXXF.

the class StringFileService method readFileString.

/**
 * 读取
 *
 * @return
 */
default Observable<String> readFileString(File file) {
    return Observable.defer(new Supplier<ObservableSource<? extends String>>() {

        @Override
        public ObservableSource<? extends String> get() throws Throwable {
            if (FileUtils.isFileExists(ApplicationProvider.applicationContext, file)) {
                try (FileReader fr = new FileReader(file)) {
                    char[] bt = new char[1024];
                    StringBuffer sb = new StringBuffer();
                    while (fr.read(bt) != -1) {
                        sb.append(bt);
                        java.util.Arrays.fill(bt, (char) 0);
                    }
                    return Observable.just(sb.toString());
                }
            }
            return Observable.empty();
        }
    }).subscribeOn(Schedulers.io());
}
Also used : Supplier(io.reactivex.rxjava3.functions.Supplier) FileReader(java.io.FileReader)

Example 29 with Supplier

use of io.reactivex.rxjava3.functions.Supplier in project xxf_android by NBXXF.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {

        @Override
        public void accept(Throwable throwable) throws Throwable {
        }
    });
    Observable.defer(new Supplier<ObservableSource<Integer>>() {

        @Override
        public ObservableSource<Integer> get() throws Throwable {
            Log.d("========>测试 开始执行重试:", "" + pageIndex);
            return Observable.just(pageIndex).map(new Function<Integer, Integer>() {

                @Override
                public Integer apply(Integer integer) throws Throwable {
                    if (integer < 3) {
                        Log.d("========>测试 异常:", "" + integer);
                        throw new RuntimeException("");
                    }
                    return integer;
                }
            });
        }
    }).retry(3, new Predicate<Throwable>() {

        @Override
        public boolean test(Throwable throwable) throws Throwable {
            if (throwable instanceof RuntimeException) {
                Log.d("========>测试  重试:", "" + System.currentTimeMillis());
                pageIndex += 1;
                return true;
            }
            return false;
        }
    }).subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Throwable {
            Log.d("========>测试 结果:", "" + integer);
        }
    });
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    binding.change.setText("normal");
    binding.change.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(v.getContext(), NormalRecyclerViewActivity.class).putExtra("xx", "77463"));
        }
    });
    setContentView(binding.getRoot());
    System.out.println("==========>onChildViewAttachedToWindow  init");
    // adapter.setHasStableIds(true);
    binding.recyclerView.setAdapter(adapter);
    // 删除-> 改变焦点(上一个)  后删除当前
    // binding.recyclerView.find
    // 创建第五条
    binding.recyclerView.setEdgeEffectFactory(new EdgeSpringEffectFactory(0.5f, 0.5f));
    binding.recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {

        @Override
        public void onChildViewAttachedToWindow(@NonNull View view) {
            RecyclerView.ViewHolder containingViewHolder = binding.recyclerView.findContainingViewHolder(view);
            if (containingViewHolder.getAdapterPosition() == 5) {
                // requestfoucs
                binding.recyclerView.removeOnChildAttachStateChangeListener(this);
            }
            System.out.println("==========>onChildViewAttachedToWindow:AdapterPosition:" + containingViewHolder.getAdapterPosition() + "  LayoutPosition:" + containingViewHolder.getLayoutPosition() + "  hash:" + containingViewHolder.itemView);
        }

        @Override
        public void onChildViewDetachedFromWindow(@NonNull View view) {
        }
    });
    sectionMap.clear();
    sectionMap.put(0, "第一个分组");
    sectionMap.put(3, "第2个分组");
    Paint paint = new Paint();
    paint.setTextSize(DensityUtil.sp2px(13));
    paint.setColor(Color.RED);
    paint.setAntiAlias(true);
    Paint background = new Paint();
    background.setColor(Color.WHITE);
    binding.recyclerView.addItemDecoration(new SectionItemDecoration(new SectionProvider() {

        @NotNull
        @Override
        public TreeMap<Integer, String> onProvideSection() {
            return sectionMap;
        }
    }, paint, background, DensityUtil.sp2px(30), DensityUtil.sp2px(16)));
    List<String> list = new ArrayList<>();
    int count = new Random().nextInt(50);
    for (int i = 0; i < count; i++) {
        // list.add("i" + new Random().nextInt(100));
        list.add("i" + i);
    }
    adapter.bindData(true, list);
    binding.refresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            List<String> list = new ArrayList<>();
            int count = new Random().nextInt(50);
            for (int i = 0; i < count; i++) {
                // list.add("i" + new Random().nextInt(100));
                list.add("i" + i);
            }
            adapter.bindData(true, list);
            Log.d("=======>list:", "" + list);
        }
    });
    binding.insert.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter.addItem(0, "hello");
        }
    });
    binding.insertLast.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter.addItem("hello foo");
        }
    });
    binding.delete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter.removeItem(0);
        }
    });
    binding.loadMore.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            List<String> list = new ArrayList<>();
            int count = new Random().nextInt(50);
            for (int i = 0; i < count; i++) {
                // list.add("i" + new Random().nextInt(100));
                list.add("i" + i);
            }
            adapter.addItems(list);
        }
    });
}
Also used : ArrayList(java.util.ArrayList) Predicate(io.reactivex.rxjava3.functions.Predicate) SectionProvider(com.xxf.view.recyclerview.itemdecorations.section.SectionProvider) Function(io.reactivex.rxjava3.functions.Function) Random(java.util.Random) ArrayList(java.util.ArrayList) List(java.util.List) Intent(android.content.Intent) Paint(android.graphics.Paint) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) EdgeSpringEffectFactory(com.xxf.view.recyclerview.adapter.EdgeSpringEffectFactory) Paint(android.graphics.Paint) ObservableSource(io.reactivex.rxjava3.core.ObservableSource) RecyclerView(androidx.recyclerview.widget.RecyclerView) SectionItemDecoration(com.xxf.view.recyclerview.itemdecorations.section.SectionItemDecoration)

Example 30 with Supplier

use of io.reactivex.rxjava3.functions.Supplier in project RxJava by ReactiveX.

the class ObservableCollectWithCollectorTest method collectorAccumulatorCrashToObservable.

@Test
public void collectorAccumulatorCrashToObservable() {
    BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1);
    source.collect(new Collector<Integer, Integer, Integer>() {

        @Override
        public Supplier<Integer> supplier() {
            return () -> 1;
        }

        @Override
        public BiConsumer<Integer, Integer> accumulator() {
            return (a, b) -> {
                throw new TestException();
            };
        }

        @Override
        public BinaryOperator<Integer> combiner() {
            return (a, b) -> a + b;
        }

        @Override
        public Function<Integer, Integer> finisher() {
            return a -> a;
        }

        @Override
        public Set<Characteristics> characteristics() {
            return Collections.emptySet();
        }
    }).toObservable().test().assertFailure(TestException.class);
    assertFalse(source.hasSubscribers());
}
Also used : java.util(java.util) Observer(io.reactivex.rxjava3.core.Observer) TestException(io.reactivex.rxjava3.exceptions.TestException) java.util.stream(java.util.stream) RxJavaTest(io.reactivex.rxjava3.core.RxJavaTest) IOException(java.io.IOException) Test(org.junit.Test) io.reactivex.rxjava3.processors(io.reactivex.rxjava3.processors) TestHelper(io.reactivex.rxjava3.testsupport.TestHelper) TestObserver(io.reactivex.rxjava3.observers.TestObserver) Assert.assertFalse(org.junit.Assert.assertFalse) Observable(io.reactivex.rxjava3.core.Observable) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) Disposable(io.reactivex.rxjava3.disposables.Disposable) java.util.function(java.util.function) TestException(io.reactivex.rxjava3.exceptions.TestException) RxJavaTest(io.reactivex.rxjava3.core.RxJavaTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)37 TestException (io.reactivex.rxjava3.exceptions.TestException)33 Observable (io.reactivex.rxjava3.core.Observable)13 IOException (java.io.IOException)9 InOrder (org.mockito.InOrder)8 java.util (java.util)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Disposable (io.reactivex.rxjava3.disposables.Disposable)5 Supplier (io.reactivex.rxjava3.functions.Supplier)5 ImmediateThinScheduler (io.reactivex.rxjava3.internal.schedulers.ImmediateThinScheduler)5 TestObserver (io.reactivex.rxjava3.observers.TestObserver)5 Observer (io.reactivex.rxjava3.core.Observer)4 BooleanSubscription (io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription)4 ImmutableList (com.google.common.collect.ImmutableList)3 io.reactivex.rxjava3.processors (io.reactivex.rxjava3.processors)3 TestHelper (io.reactivex.rxjava3.testsupport.TestHelper)3 java.util.function (java.util.function)3 java.util.stream (java.util.stream)3 Assert.assertFalse (org.junit.Assert.assertFalse)3 SQLUtils (com.alibaba.druid.sql.SQLUtils)2