标签: reactive-programming

我们如何在 Shiny 应用程序中使用“names()”或名称“reactiveVal”的替代方案?

names()我尝试在闪亮的应用程序内部使用reactiveVal但没有成功。


这可能吗?在闪亮的应用程序中命名反应值的替代方法是什么?


我的第一次尝试抛出一个错误:

names(r()) <- "something"
Run Code Online (Sandbox Code Playgroud)

名称错误(r())<-“某事”:赋值左侧无效(NULL)

我的第二次尝试也是如此:

names(r) <- "something"
Run Code Online (Sandbox Code Playgroud)

名称(r)<-“某物”中的错误:名称()应用于非向量


这是一个最小的示例应用程序:

library(shiny)

ui <- fluidPage(mainPanel(textOutput("text")))

server <- function(input, output) {
  r <- reactiveVal(1)
  # names(r) <- "something"
  output$text <- renderText(
    paste0("The reactiveVal is ", r(),". It's name is ", names(r()),"."))
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

r names reactive-programming shiny

5
推荐指数
1
解决办法
1602
查看次数

使用项目反应器将验证纳入反应链

我想组成一个反应器链,基本上如下:

  1. 验证提交的User属性,例如 的长度firstName或lastName的有效性email。我会使用下面的验证器。
  2. 验证提交的内容email尚未被其他人使用。我会为此目的使用反应式存储库。
  3. User如果以上所有验证检查都通过,则保存。

用户:

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
}
Run Code Online (Sandbox Code Playgroud)

反应式存储库:

public interface UserRepository extends ReactiveCrudRepository<User, Long> {

    @Query("select id, first_name, last_name, email from user u where u.email = :email")
    Mono<User> findByEmail(String email);
}
Run Code Online (Sandbox Code Playgroud)

验证器:

@Component
public class UserValidator implements Validator {

    private final static String EMAIL = "email";
    private static …
Run Code Online (Sandbox Code Playgroud)

reactive-programming project-reactor spring-webflux

5
推荐指数
1
解决办法
2666
查看次数

如何在prometheus中公开webClient指标?

我想将 WebClient 调用的指标从服务公开到下游系统,需要诸如请求计数、最短、最长时间响应之类的指标。

我想知道如何为反应式网络客户端编写仪表。

这是一个 MeterBinder 示例,我有兴趣将其与 Webclient 一起使用。

class Metrics : MeterBinder {
    override fun bindTo(registry: MeterRegistry) {
        Gauge.builder("metrics", Supplier { Math.random() })
                .baseUnit("status")
                .register(registry)
    }
}
Run Code Online (Sandbox Code Playgroud)

spring reactive-programming kotlin prometheus spring-webclient

5
推荐指数
1
解决办法
8214
查看次数

rxjs Observable 相对于 DOM 事件有什么优点?

我一直在研究 rxjs 和反应式编程,但有些东西我还不太明白。例如,我想获取keyup简单输入上的事件结果,映射它,并将映射结果设置为另一个div内容:

const root = $('#root'),
      input = root.find('#some-input'),
      result = root.find('#result');
Run Code Online (Sandbox Code Playgroud)

使用 rxjs,我可以这样做:

const keyupObs = fromEvent(input, 'keyup');
const mapper = keyupObs.pipe(
    map(e => $(e.target)),
    tap(t => result.html(t.val()))
).subscribe(t => console.log(t));
Run Code Online (Sandbox Code Playgroud)

使用 jquery 驱动的事件,我可以编写:

input.on('keyup', e => result.html($(e.currentTarget).val()));
Run Code Online (Sandbox Code Playgroud)

这是更少的代码,对于像我这样的初学者来说,似乎与我使用 rxjs 编写的代码没有太大区别。那么使用 rxjs 的主要优点是什么?为什么我应该使用它而不是 DOM 驱动事件(在本例中使用 jQuery)?

javascript jquery reactive-programming rxjs

5
推荐指数
1
解决办法
1033
查看次数

shouldComponentUpdate 相当于功能组件,忽略状态更改

我的代码有一个组件,它接受两个 props 并拥有自己的内部状态。
仅当组件的 props 更改时,组件才应重新渲染。状态更改不应触发重新渲染。
此行为可以使用基于类的组件和自定义shouldComponentUpdate函数来实现。
然而,这将是代码库中第一个基于类的组件。一切都是通过功能组件和钩子完成的。因此我想知道是否可以使用功能组件来编写所需的功能。

在一些没有解决实际问题的答案之后,我想我必须重新表述我的问题。这是一个包含两个组件的最小示例:

  • Inner 需要一个 prop 并具有状态。这是有问题的组件。状态更改后不得重新渲染。道具更改应该触发重新渲染。
  • 外层是内层的包裹物。它在这个问题的范围内没有任何意义,只是为 Inner 提供道具并模拟道具变化。

为了演示所需的功能,我使用基于类的组件实现了 Inner。该代码的实时版本可以在codesandbox 上找到。如何将其迁移到功能组件:

Inner.tsx:

import React, { Component } from 'react'

interface InnerProps{outerNum:number}
interface InnerState{innerNum:number}

export default class Inner extends Component<InnerProps, InnerState> {
    state = {innerNum:0};

    shouldComponentUpdate(nextProps:InnerProps, nextState:InnerState){
        return this.props != nextProps;
    }
    render() {
        return (
            <button onClick={()=>{
                this.setState({innerNum: Math.floor(Math.random()*10)})
            }}>
                {`${this.props.outerNum}, ${this.state.innerNum}`}
            </button>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

外部.tsx:

import React, { useState } from "react";
import Inner from …
Run Code Online (Sandbox Code Playgroud)

javascript reactive-programming reactjs react-hooks

5
推荐指数
1
解决办法
7649
查看次数

Project Reactor block() 与 StepVerifier 中的正确测试模式

最近我注意到我的团队在如何在 Reactor 中编写测试时遵循两种方法。第一个是借助.block()方法。它看起来像这样:

@Test
void set_entity_version() {
    Entity entity = entityRepo.findById(ID)
                              .block();
    assertNotNull(entity);
    assertFalse(entity.isV2());

    entityService.setV2(ID)
                 .block();

    Entity entity = entityRepo.findById(ID)
                              .block();

    assertNotNull(entity);
    assertTrue(entity.isV2());
}
Run Code Online (Sandbox Code Playgroud)

第二个是关于使用StepVerifier. 它看起来像这样:

@Test
void set_entity_version() {

    StepVerifier.create(entityRepo.findById(ID))
                .assertNext(entity -> {
                    assertNotNull(entity);
                    assertFalse(entity.isV2());
                })
                .verifyComplete();
            
    StepVerifier.create(entityService.setV2(ID)
                                     .then(entityRepo.findById(ID)))
                .assertNext(entity -> {
                    assertNotNull(entity);
                    assertTrue(entity.isV2());
                })
                .verifyComplete();
}
Run Code Online (Sandbox Code Playgroud)

以我的拙见,第二种方法看起来更具反应性。此外,官方文档对此也说得很清楚:

StepVerifier 提供了一种声明性方式,通过表达对订阅时将发生的事件的期望,为异步发布者序列创建可验证脚本。

不过,我真的很好奇,应该鼓励使用什么方式作为在 Reactor 中进行测试的主要途径。该.block()方法应该完全放弃还是在某些情况下可能有用?如果是,那么此类案例是什么?

谢谢!

testing unit-testing reactive-programming project-reactor

5
推荐指数
1
解决办法
5016
查看次数

如何在Spring Webflux中不阻塞地从Mono对象中提取数据?

我正在使用 Postman 向我的 Spring 应用程序发送 POST 请求。该请求有一个 JSON 正文,如下所示:

{
        "documents": [
            {
                "id": "1",
                "text": "Piece of text 1",
                "lang": "en"
            },
            {
                "id": "2",
                "text": "Piece of text 2",
                "lang": "en"
            }
        ],
        "domain": "hr",
        "text_key": "text"
    }

Run Code Online (Sandbox Code Playgroud)

我设置了一个方法来处理这些 POST 请求,并且我需要能够从请求正文中提取上述 JSON 数据而不阻塞。我现在的方法看起来像这样:

public void requestBody(ServerRequest request) {


      Mono<String> bodyData = request.bodyToMono(String.class);

      System.out.println("\nsubscribing to the Mono.....");

      bodyData.subscribeOn(Schedulers.newParallel("requestBody")).subscribe(value -> {
        log.debug(String.format("%n value consumed: %s" ,value));
      });

}
Run Code Online (Sandbox Code Playgroud)

然而,这没有任何作用。我尝试查看Spring Reactive get body JSONObject using ServerRequest AND Getting String body …

java spring reactive-programming spring-boot spring-webflux

5
推荐指数
1
解决办法
9413
查看次数

当要旋转的对象的父对象发生旋转时如何使用 SparkAR 的 LookAt

在 SparkAR 中,我希望有一个toRotate始终看着相机的元素(称为 ),类似于此处已经提出的问题(但接受的解决方案对我来说并不令人满意,而且我没有足够的声誉来回答并发表评论)。

问题是这个元素位于无法修改的层次结构中:顺序必须绝对如屏幕截图root->planeTracker->parent->toRotate所示(似乎我没有足够的声誉来嵌入图像)。

通过使用该lookAt函数(感谢这个 github 存储库,我明白我必须创建一个具有相同本地位置的toRotateDuplicate同级文件toRotate,然后使用它的转换),我可以让它在编辑器中正常工作,但是一旦我尝试使用它我的设备toRotate有一个奇怪的旋转。

经过一些测试,我可以看出问题是由于planeTracker仅在编辑器上具有等于 Quaternion.Identity 的旋转,而在设备上该值有所不同。
事实也证明了这一点,如果planeTracker用空节点替换 并对其应用非恒等旋转,即使在编辑器上我们也会遇到“奇怪的旋转”问题。

这是我的代码:

const Scene = require("Scene");
const Reactive = require("Reactive");

const find = e => Scene.root.findFirst(e);

(async function () {
  const toRotate = await find('toRotate');
  const toRotateDuplicate = await find('toRotateDuplicate');
  const camera = await find('Camera');
  toRotate.worldTransform.rotation = toRotateDuplicate.worldTransform.lookAt(camera.worldTransform.position).rotation;
})();
Run Code Online (Sandbox Code Playgroud)

由于我使用的是世界变换,所以我不应该有旋转问题,对吗?
那我该怎么办?

请注意,此处接受的解决方案对我不起作用:如果相机正在查看对象的中心,则该对象只会查看相机,而且如果我移动相机而不旋转它,我可以看到该对象是不更新其旋转以继续查看相机。

javascript reactive-programming spark-ar-studio

5
推荐指数
1
解决办法
842
查看次数

反应式管道中的后台任务(即发即忘)

我有一个反应式管道来处理传入的请求。对于每个请求,我需要调用一个与业务相关的函数 ( doSomeRelevantProcessing)。

完成后,我需要通知一些外部服务发生了什么。管道的那部分不应增加总体响应时间。此外,通知此外部系统并不是业务关键:在管道的主要部分完成后给出快速响应比确保通知成功更重要。

据我所知,在后台运行某些内容而不减慢整个过程的唯一方法是直接在管道中订阅,从而实现“一劳永逸”的心态。

除了在 内订阅之外,还有其他好的选择吗flatmap?我有点担心如果通知外部服务花费的时间比原始处理时间长并且同时收到大量请求会发生什么情况。这是否会导致内存耗尽或整个进程阻塞?

fun runPipeline(incoming: Mono<Request>) = incoming
    .flatMap { doSomeRelevantProcessing(it) } // this should not be delayed
    .flatMap { doBackgroundJob(it) } // this can take a moment, but is not super critical

fun doSomeRelevantProcessing(request: Request) = Mono.just(request) // do some processing

fun doBackgroundJob(request: Request) = Mono.deferContextual { ctx: ContextView ->
    val notification = "notification" // build an object from context

    // this uses non-blocking HTTP (i.e. webclient), so it can …
Run Code Online (Sandbox Code Playgroud)

reactive-programming project-reactor spring-webflux

5
推荐指数
1
解决办法
1439
查看次数

无法调用“reactor.core.publisher.Mono.thenReturn(Object)”,因为返回值为 null

我试图通过模拟存储库类来为 createEmployee 和 updateEmployee 编写测试用例。但是,它失败并出现以下错误。

注意:其他 find、findAll 方法都工作正常。

java.lang.NullPointerException: Cannot invoke "reactor.core.publisher.Mono.thenReturn(Object)" because the return value of "com.springflexcounchdb.dao.IEmployeeDAO.create(com.springflexcounchdb.model.Employee)" is null
    at com.springflexcounchdb.test.service.EmployeeServiceTest.createEmployeeTest(EmployeeServiceTest.java:71)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:93)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at …
Run Code Online (Sandbox Code Playgroud)

junit mockito reactive-programming spring-webflux

5
推荐指数
1
解决办法
6223
查看次数