围绕.NET 4.0中的新Reactive Framework进行了大量宣传.虽然我认为我不知道它的基本概念,但我并没有完全销售,因此它非常有用.你能想出一个很好的例子(中途易于理解),它完全展示了Rx的力量和实用性吗?展示一些使用Rx完成生活变得更容易的东西.
我有一个参数化的休息调用应该每隔五秒用不同的参数执行:
Observable<TResult> restCall = api.method1(param1);
Run Code Online (Sandbox Code Playgroud)
我需要创建一个Observable<TResult>将每隔5秒轮询一次restCall ,其中包含param1的不同值.如果api调用失败,我需要收到错误并在5秒内进行下一次调用.只有在restCall完成(成功/错误)时才应测量调用之间的间隔.
我目前正在使用RxJava,但.NET示例也会很好.
这基于此SO中提供的代码:编写Rx"RetryAfter"扩展方法
我正在使用Markus Olsson的代码(目前仅进行评估),之前有人要求我试图在Github上抓住Markus,但是在我工作的地方被阻止了,所以我觉得我唯一能做的就是问在这里.很抱歉,如果这与任何人都很糟糕.
所以我在一个小的演示中使用以下代码:
class Attempt1
{
private static bool shouldThrow = true;
static void Main(string[] args)
{
Generate().RetryWithBackoffStrategy(3,
MyRxExtensions.ExponentialBackoff,
ex =>
{
return ex is NullReferenceException;
}, Scheduler.TaskPool)
.Subscribe(
OnNext,
OnError
);
Console.ReadLine();
}
private static void OnNext(int val)
{
Console.WriteLine("subscriber value is {0} which was seen on threadId:{1}",
val, Thread.CurrentThread.ManagedThreadId);
}
private static void OnError(Exception ex)
{
Console.WriteLine("subscriber bad {0}, which was seen on threadId:{1}",
ex.GetType(),
Thread.CurrentThread.ManagedThreadId);
}
static IObservable<int> Generate()
{
return Observable.Create<int>(
o =>
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试命中一个服务并返回一个对象列表,在它返回给订阅者之前,我想对列表中的每个对象进行另一个同步调用,以进行另一个服务调用来设置一个丢失的字段.我已成功完成所有调用,但订阅者返回的对象具有此字段,我需要将其设置为null.这是我的代码示例:
示例服务:
rx.Observable<List<ExampleObject>> getExampleObject();
rx.Observable<MissingObject> getMissingObjectByFoo(@Path("foo") String foo);
Run Code Online (Sandbox Code Playgroud)
示例类:
public class ExampleObject {
String foo;
MissingObject bar;
public String getFoo() {
return this.foo;
}
public void setFoo(String value) {
this.foo = value;
}
public MissingObject getBar() {
return this.bar;
}
public void setBar(MissingObject value) {
this.bar = value;
}
}
Run Code Online (Sandbox Code Playgroud)
示例实施:
mService.getExampleObject().flatMap(new Func1<List<ExampleObject>, Observable<?>>() {
@Override
public Observable<List<ExampleObject>> call(List<ExampleObject> exampleObjects) {
for (ExampleObject entry : exampleObjects) {
String foo = entry.getFoo();
mService.getMissingObjectByFoo(foo)
.subscribeOn(mScheduler.backgroundThread())
.observeOn(mScheduler.mainThread())
.subscribe(new Subscriber<MissingObject>() {
@Override
public void …Run Code Online (Sandbox Code Playgroud) 我尝试从swap api查询所有人的数据.URL swapi.co/api/people返回一个带有人员数组和URL(swapi.co/api/people/?page=2)的对象,我从中获取下一个数据.我想要做的是订阅方法每次新页面可用时更新角度组件.
我是反应式编程模型的新手.如何实现while循环或一系列Observable?
这适用于第一页:
getAllPeople(): Observable<Person[]> {
let nextUrl = http://swapi.co/api;
let source = Observable.create(observer => {
this.http.get(nextUrl, { headers: this.headers })
.map(response => {
let body = response.json();
nextUrl = body.next;
return nextUrl != null ? body.results as Person[] : null;
}
)
.retry(5)//send same request based on the url of the previous request till the field next is null
.catch(error => observer.error(error))
.subscribe(persons => {
if (persons !== null) {
observer.next(persons)
}
}
);
//observer.complete(); …Run Code Online (Sandbox Code Playgroud) 在Spring Data中,我们PagingAndSortingRepository继承了它CrudRepository.在反应式Spring数据中,我们只有
ReactiveSortingRepository继承自ReactiveCrudRepository.我们怎么能以反应的方式进行分页呢?例如,我们将来能够做到这一点ReactivePagingAndSortingRepository吗?
因此,我的用例是在使用Project Reactor以反应式样式编程时使用Spring Webflux应用程序中的Kafka消息,并按照从Kafka收到消息的相同顺序对每个消息执行非阻塞操作.系统也应该能够自行恢复.
以下是设置为使用的代码段:
Flux<ReceiverRecord<Integer, DataDocument>> messages = Flux.defer(() -> {
KafkaReceiver<Integer, DataDocument> receiver = KafkaReceiver.create(options);
return receiver.receive();
});
messages.map(this::transformToOutputFormat)
.map(this::performAction)
.flatMapSequential(receiverRecordMono -> receiverRecordMono)
.doOnNext(record -> record.receiverOffset().acknowledge())
.doOnError(error -> logger.error("Error receiving record", error))
.retryBackoff(100, Duration.ofSeconds(5), Duration.ofMinutes(5))
.subscribe();
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我所做的是:从Kafka获取消息,将其转换为用于新目标的对象,然后将其发送到目标,然后确认偏移以将消息标记为已消耗和处理.以与从Kafka消耗的消息相同的顺序确认偏移量是至关重要的,这样我们就不会将偏移量移动到未完全处理的消息之外(包括将一些数据发送到目的地).因此我用a flatMapSequential来确保这一点.
为简单起见,我们假设该transformToOutputFormat()方法是一种身份变换.
public ReceiverRecord<Integer, DataDocument> transformToOutputFormat(ReceiverRecord<Integer, DataDocument> record) {
return record;
}
Run Code Online (Sandbox Code Playgroud)
该performAction()方法需要通过网络执行某些操作,例如调用HTTP REST API.因此适当的API返回Mono,这意味着需要订阅链.此外,我需要ReceiverRecord通过此方法返回,以便可以在上面的flatMapSequential()运算符中确认偏移量.因为我需要Mono订阅,我正在flatMapSequential上面使用.如果没有,我可以用一个map代替.
public Mono<ReceiverRecord<Integer, DataDocument>> performAction(ReceiverRecord<Integer, DataDocument> record) {
return Mono.just(record)
.flatMap(receiverRecord ->
HttpClient.create()
.port(3000)
.get()
.uri("/makeCall?data=" + …Run Code Online (Sandbox Code Playgroud) java reactive-programming apache-kafka project-reactor spring-webflux
我正在尝试使用Kotlin Flows. 这是我现在正在尝试的
flowOf(
remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
.catch { error -> Timber.e(error) },
remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
).flattenConcat().collect {
Timber.i("Response Received")
}
Run Code Online (Sandbox Code Playgroud)
这里的问题collect是只在getDataFromServer返回时调用。我的期望是我应该在几毫秒后从缓存中获取第一个事件,然后从服务器获取第二个事件。在这种情况下,"Response Received"会打印两次,但会立即一个接一个地打印。
在此其他变体中,"Response Received"仅在getDataFromServer()返回后打印一次。
remoteDataSource.getDataFromCache() // suspending function returning Flow<Data>
.catch { error -> Timber.e(error) }
.flatMapConcat {
remoteDataSource.getDataFromServer() // suspending function returning Flow<Data>
}
.collect {
Timber.i("Response Received")
}
Run Code Online (Sandbox Code Playgroud)
我Flowable.concat()之前使用过 RxJava ,它运行良好。Kotlin Flows 中是否有可以模拟这种行为的东西?
android reactive-programming kotlin kotlin-coroutines kotlin-flow
上周我回答了一个 RxJS问题,在那里我与另一位社区成员进行了讨论:“我应该为每个特定的副作用创建订阅,还是应该尽量减少订阅?” 我想知道在完全反应式应用程序方法或何时从一种切换到另一种方法方面使用什么方法。这将帮助我和其他人避免不必要的讨论。
设置信息
什么是副作用(Angular 示例)
value$ | async)@Output event = event$)示例用例:
foo: () => void; bar: (arg: any) => voidhttp$: Observable<any>; click$: Observable<void>foo在http$发出后调用并且不需要值bar在click$发出后调用,但需要当前值http$案例:为每个特定的副作用创建订阅
const foo$ = http$.pipe(
mapTo(void 0)
);
const bar$ = http$.pipe(
switchMap(httpValue => click$.pipe(
mapTo(httpValue)
)
);
foo$.subscribe(foo);
bar$.subscribe(bar);
Run Code Online (Sandbox Code Playgroud)
案例:一般最小化订阅
http$.pipe(
tap(() => foo()),
switchMap(httpValue => click$.pipe( …Run Code Online (Sandbox Code Playgroud) 假设我们有一个实例o.s.w.reactive.function.server.ServerResponse.
获取其主体内容的正确方法是什么,换句话说,如何实现fetchBodyAsString功能?
test(){
ServerResponse response = getResponseFromService("mock data");
String body = fetchBodyAsString(response);
assertEquals("hello", body);
}
Run Code Online (Sandbox Code Playgroud)
您能否详细说明一下为什么ServerResponse所有内容都有方法(cookies(), headers(), statusCode()),但响应正文却没有?我想应该有一种方法可以用方法获取主体 writeTo(),尽管如何使用它绝对是模糊的。
java spring server-response reactive-programming spring-webflux
java ×3
android ×2
c# ×2
javascript ×2
rx-java ×2
rxjs ×2
typescript ×2
.net ×1
angular ×1
angularjs ×1
apache-kafka ×1
async-await ×1
kotlin ×1
kotlin-flow ×1
retrofit ×1
spring ×1
spring-data ×1