gpt4 book ai didi

android - 如何在 RxJava2 (Android) 中创建一个没有输入值但会生成一个字符串的流?

转载 作者:行者123 更新时间:2023-11-30 00:37:05 27 4
gpt4 key购买 nike

在 Android 中,我想在单独的线程(IO 线程)上调用 AdvertisingIdClient.getAdvertisingIdInfo(getContext()).getId() 并在主线程上处理字符串。

我不想用 RxJava2 做这个。这就是我现在拥有的:(有效)

SingleOnSubscribe<String> source = new SingleOnSubscribe<String>() {
@Override
public void subscribe(SingleEmitter<String> e) throws Exception {
e.onSuccess(AdvertisingIdClient.getAdvertisingIdInfo(getContext()).getId());
}
};

Single.create(source)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Timber.e(throwable.getMessage());
}
})
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
advertisingId = s;
}
});

我更喜欢的是,这纯粹是品味,如果我可以“只是”创建流并在方法流中处理它。如:(警告, super 伪代码)

Completable
.empty()
.produce(() -> String {
return makeString();
})
.sub/obs-On()...
.subscribe(coolString -> {mVariable = coolString})

所以,创建一个 Observable 并通过执行一些函数将其变成一个 Observable。

最佳答案

像这个例子一样使用 defer 或 fromCallable:

Observable<String> stringObservable = Observable.fromCallable(() -> {
return getStuff();
});

测试

@Test
public void fromCallable() throws Exception {
Observable<String> stringObservable = Observable.fromCallable(() -> {
return getStuff();
});

ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> {
return new Thread(runnable, "myFancyThread");
});
Scheduler scheduler = Schedulers.from(executorService);

TestObserver<String> test = stringObservable.subscribeOn(scheduler)
.test();

test.await()
.assertResult("wurst");

assertThat(test.lastThread().getName()).contains("myFancyThread");
}

private String getStuff() {
return "wurst";
}

关于android - 如何在 RxJava2 (Android) 中创建一个没有输入值但会生成一个字符串的流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251062/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com