我想知道如何使用 Reactor 创建“逻辑流”。
让我们假设我想实现以下场景:
作为输入,我有对象要保存在数据库中。作为输出,我想获得 Mono 表示执行消息。
选项 1: 如果要保存的对象已填充所有字段,则我执行附加操作,将其保存到数据库并最终返回“ Success”消息
选项 2:如果要保存的对象至少有一个字段未填写,我返回“ Error”
我已经创建了这样的代码:
Mono<String> message = Mono.just(new User("Bob the Reactor master")) // user with name = can be saved
.flatMap(user -> {
if(user.getName() != null && user.getName().length() > 1){
// Perform additional operations e.g. user.setCreatedDate(new Date())
// Save to repository e.g. repository.save(user)
return Mono.just("Success!");
}
else{
return Mono.just("Error!");
}
})
.doOnNext(System.out::println); // print stream result
message.subscribe();
Run Code Online (Sandbox Code Playgroud)
这段代码是 100% 反应性的吗(有它的所有好处)?如果没有,那么它会是什么样子?
我想有多个订阅来对一个可观察的事件做出反应,但我也想记录该事件,所以我通过一个do()操作员来记录它。
问题是,我创建的每个订阅都会记录一次事件!
我目前正在通过创建 aSubject并next从事件回调中调用它来解决这个问题,这允许我记录一次事件并触发多个订阅。
以下是一些演示该问题的代码:https : //stackblitz.com/edit/rxjs-xerurd
我有一种感觉,我错过了一些东西,难道没有更“RxJS”的方式来做到这一点吗?
编辑:
我不是在要求区分热和冷可观察量,实际上我使用的是热可观察量 - 由它创建fromEvent()并想知道为什么我可能的热事件源表现得像冷的一样。
我现在意识到 - 在阅读之后share()- 这pipe()会“改变”你可观察到的寒冷,即根据你的来源(可能是冷的,可能是热的)返回一个冷的
我试图了解 Project reactor 为应用程序代码提供的关于数据可见性的保证。例如,我希望下面的代码会失败,但经过一百万次迭代后不会失败。我正在更改线程 A 上典型 POJO 的状态并从线程 B 读取它。 Reactor 是否保证 POJO 更改在线程间可见?
public class Main {
public static void main(String[] args) {
Integer result = Flux.range(1, 1_000_000)
.map(i -> {
Data data = new Data();
data.setValue(i);
data.setValueThreeTimes(i);
data.setValueObj(i + i);
return data;
})
.parallel(250)
.runOn(Schedulers.newParallel("par", 500))
.map(d -> {
d.setValueThreeTimes(d.getValueThreeTimes() + d.getValue());
return d;
})
.sequential()
.parallel(250)
.runOn(Schedulers.newParallel("par", 500))
.map(d -> {
d.setValueThreeTimes(d.getValueThreeTimes() + d.getValue());
return d;
})
// .sequential()
.map(d -> {
if (d.getValue() * 3 != …Run Code Online (Sandbox Code Playgroud) 我有以下使用反应堆核心中的通量的反应代码:
Flux.create(sink -> ... /* listens to and receives from external source */ , FluxSink.OverflowStrategy.LATEST)
.flatMap(map -> redisHashReactiveCommands.hmset(key, map))
//.flatMap(... //want to store same data async into kafka with its own back pressure handling)
.subscribeOn(Schedulers.parallel())
.doOnNext(s -> log.debug("Redis consumed. Result -> {}", s))
.doOnComplete(() -> log.debug("On completed."))
.doOnError(exception -> log.error("Error occurred while consuming message", exception))
.subscribe();
Run Code Online (Sandbox Code Playgroud)
如您所见,我对流程的外部源 (FluxSink.OverflowStrategy.LATEST) 进行了背压处理。但是,我还想为我的进程配置背压到 redis (redisHashReactiveCommands.hmset(key, map)),因为它可能是比我的进程的外部源更大的瓶颈。我希望我需要为 redis 部分创建另一个通量并将其与这个通量链接,但是我如何实现这一点,因为 .flatMap 适用于单个项目而不是项目流?
另外,我也想将相同发出的项目存储到 Kafka 中,但是链接flapMap 似乎不起作用.. 是否有一种简单的方法将所有这些链接到一组函数调用中(外部源 -> 我的过程,我的进程-> redis,我的进程-> kafka)?
感谢 @GlennWatson 指出ReactiveUI.WPF除了ReactiveUI包之外,我还需要添加对 Nuget Package 的引用。
我有一个ReactiveObject视图模型,我想在其中使用 anOpenFileDialog来设置我的一个视图模型属性 ( PdfFilePath) 的值。我尝试过的一切都会导致The calling thread cannot access this object because a different thread owns it错误。
我意识到下面的代码不符合 MVVM,因为我在视图模型中使用了“显式引用/实例化视图的类型”的代码,但我只是在寻找一个可以工作的最小示例,以便我可以向后工作,将视图和视图模型代码分开,并最终将服务传递给我的视图模型,该服务处理整个“选择文件路径”部分。
public class ImportPdfViewModel : ReactiveObject
{
public ImportPdfViewModel()
{
SelectFilePathCommand = ReactiveCommand.Create(() =>
{
OpenFileDialog ofd = new OpenFileDialog() { };
//
if (ofd.ShowDialog() == DialogResult.OK)
PdfFilePath = ofd.FileName;
});
}
private string _PdfFilePath;
public string PdfFilePath
{
get => _PdfFilePath;
set => this.RaiseAndSetIfChanged(ref …Run Code Online (Sandbox Code Playgroud) 我使用的是 spring Spring boot 2.1.0。
public Mono<ServerResponse> getConvertXmlToJson(ServerRequest serverRequest) {
Mono<String> requestString = serverRequest.bodyToMono(String.class);
Mono<String> response = this.convertFormatService.convertXmlToJson(requestString);
return response.subscribeOn(elastic()).flatMap(rta -> ok()
.contentType(APPLICATION_JSON_UTF8)
.body(fromObject(rta)))
.switchIfEmpty(ServerResponse.badRequest().build());
}
Run Code Online (Sandbox Code Playgroud)
在其他 bean 中调用此方法
private Mono<String> converter(String function, Mono<String> stringToConverter, String setting) {
log.info("salida, {}", stringToConverter.block());
try {
Object result = invocable.invokeFunction(function, stringToConverter, setting);
log.info("{}", result);
return Mono.just((String) result);
} catch (Exception e) {
throw new ConverterException(e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
我需要传递一个字符串值,而不是 Mono,当我传递 Mono 时,答案为空。
当我尝试从 Mono 获取字符串值时,出现此错误:
{
"timestamp": "2018-11-13T03:29:02.161+0000",
"path": "/v1/convert",
"status": 500,
"error": "Internal …Run Code Online (Sandbox Code Playgroud) 我得到了一个这样的可观察对象:
const original = Observable.of({
a: this.http.get('https://jsonplaceholder.typicode.com/todos/11'),
b: this.http.get('https://jsonplaceholder.typicode.com/todos/22'),
c: this.http.get('https://jsonplaceholder.typicode.com/todos/33')
});
Run Code Online (Sandbox Code Playgroud)
我需要解析内部 observables 并在订阅处理程序中得到类似的东西:
{
a: ResponseFromServer,
b: ResponseFromServer,
c: ResponseFromServer,
}
Run Code Online (Sandbox Code Playgroud)
我应该如何解决这个问题?
谢谢。
编辑:我已经想通了,请阅读下文。
似乎没有多少人知道 *Map 运算符曾经有一个称为resultSelector第二个参数的东西。现在在 rxjs v6 中,你可以用 做同样的事情inner map,让我来告诉你。
const original = Observable.of({
a: this.http.get('https://jsonplaceholder.typicode.com/todos/11'),
b: this.http.get('https://jsonplaceholder.typicode.com/todos/22'),
c: this.http.get('https://jsonplaceholder.typicode.com/todos/33')
});
const transformed = original.pipe(
mergeMap(sourceValue =>
forkJoin(_.values(sourceValue)).pipe(map(resolvedHttpRequests => {
// here you have access to sourceValue as well as resolvedHttpRequests so you can do manual join to match the data.
})) …Run Code Online (Sandbox Code Playgroud) reactive-programming object-properties rxjs reactivex angular
我是 Spring WebFlux 的新手,正在尝试将我的 Spring MVC 应用程序转换为 webflux。我从我的服务中返回一个 Mono 单声道:
List<Store> stores = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
当我做:
mono.subscribe(stores::addAll);
dataexchange.put("stores", stores);
return Mono.just(dataexchange);
Run Code Online (Sandbox Code Playgroud)
然后作为响应将商店填充为空列表。但是,我可以在返回响应后验证 subscribe() 是否正常工作。
当我做 :
return mono.flatmap( (response) -> {
dataexchange.put("stores", response));
return Mono.just(dataexchange);
});
Run Code Online (Sandbox Code Playgroud)
然后在响应中填充商店。
有人可以解释一下这两者有什么区别吗?flatMap 是否阻塞?提前致谢 !
I'm attempting to achieve the following in the method below
- Get All Cars from Dealer X
- Create wrapper object that stores a set of all cars and another set of all manufactures 2a. Populate Cars set with the cars obtained in Step 1
- 对于每辆汽车,获得他们所有的独立制造商
- 将所有获得的制造商存储到包装对象制造商集合中
- 返回汽车和制造商的单声道
Mono<CarAndManufactures> requestCarAndManufactures(Request req) {
final String dealerId = buildDealerId(req.getDealerRegion(), req.getDealerId());
final CarAndManufactures CarAndManufactures = new CarAndManufactures();
return webSocketClient.getCars(dealerId) //note #getCars returns a Mono
.map(getCarsResponse -> getCarsResponse
.getResult()
.stream()
.map(Car::getId)
.collect(toSet()))
.map(carIds -> {
CarAndManufactures.setCars(carIds); …Run Code Online (Sandbox Code Playgroud) 我想通过 Spring WebFlux 和给定的 REST-API 执行以下操作:
问题是我不能将这两个操作组合到“一个”Mono 实例。我当前的实现是不够的,因为它阻止 Mono 实例立即执行 api 调用,而不是执行它们的反应性。
我的非反应式实现:
public Mono cleanUpUploadedFiles() {
WebClient webClient = this.getWebClient();
// get all files / directories
Mono<FilesOverview> filesOverviewMono = this.getResource("/files", FilesOverview.class);
FilesOverview filesOverview = filesOverviewMono.block(); // TODO: prevent blocking mono
// delete file / directory one by one
for (FileOverview file : filesOverview.getFiles()) {
ClientResponse clientResponse;
clientResponse = webClient
.delete()
.uri(String.format("/files/local/%s", file.getName()))
.exchange()
.block(); // TODO: prevent blocking mono
if (clientResponse …Run Code Online (Sandbox Code Playgroud) java ×5
rxjs ×2
angular ×1
c# ×1
java-8 ×1
javascript ×1
mvvm ×1
reactiveui ×1
reactivex ×1
reactor ×1
spring-boot ×1