当前位置:网站首页>Simple understanding of responsive programming
Simple understanding of responsive programming
2022-06-23 23:39:00 【eeaters】
Responsive programming
Reference website
Programming model
Non blocking asynchronous programming , Mapping is essentially a callback function in code , Corresponding to the reactive programming model is the traditional Command programming ;
- Instruction programming model : Synchronous blocking , Tell the computer What to do , What controls is the state
- Responsive programming model : Asynchronous non-blocking , Tell the computer What to do , Control is the goal
The basic object
With Java 9 Of api For example :
Flow.Publisher<T>
Publisher , The object of data input , T Represents the type of data
@FunctionalInterface
public static interface Publisher<T> {
public void subscribe(Subscriber<? super T> subscriber);
}Flow.Subscription<T>
An intermediary agent , Publishers and subscribers have no direct contact , Instead, it controls the transmission of data Separate from data and changes in data , Thus reducing the coupling between functions
public static interface Subscription {
public void request(long n);
public void cancel();
}Flow.Subscriber<T>
subscriber ,T Describe the type of data , The reactions in four cases are specified respectively :
- What if you receive a subscription invitation ? This behavior is caused by onSubscribe
- The implementation of this method determines . What if data is received ? This behavior is caused by onNext
- The implementation of this method determines . What to do if you encounter an error ? This behavior is caused by onError
- The implementation of this method determines . What to do if the data transmission is completed ? This behavior is caused by onComplete The implementation of this method determines .
public static interface Subscriber<T> {
public void onSubscribe(Subscription subscription);
public void onNext(T item);
public void onError(Throwable throwable);
public void onComplete();
}Flow.Processor<T>
processor , At the same time Publisher and Subscriber, That is to do a connecting role , It is an intermediate process of data processing during the execution of a stream ;
public static interface Processor<T,R> extends Subscriber<T>, Publisher<R> {
}Simple try
Main task
Use Flow Of api Realization : a=b+c a: Suppose you need to know the day of the week when an event ends b: The start time of the data is the day of the week Don't work hard on Friday, Saturday and Sunday , Until Monday , The actual start time is Monday , c: It will take several days to deal with this matter , Monday It takes two days , Tuesday, Wednesday and Thursday take a day ,
NOTE | No multithreading , Just want to know something about the responsive code execution |
|---|
The first stage
bc Do not split , Fast business implementation
Publisher
public class TimePublisher implements Flow.Publisher<LocalDate> {
public final LinkedList<LocalDate> items;
public TimePublisher(LinkedList<LocalDate> items) {
this.items = items;
}
@Override
public void subscribe(Flow.Subscriber subscriber) {
subscriber.onSubscribe(new TimeSubscription(subscriber, items));
}
}Subscription
public class TimeSubscription implements Flow.Subscription {
private final Flow.Subscriber<LocalDate> subscriber;
private LinkedList<LocalDate> list;
public TimeSubscription(Flow.Subscriber<LocalDate> subscriber, LinkedList<LocalDate> list) {
this.subscriber = subscriber;
this.list = list;
}
@Override
public void request(long n) {
if (list.isEmpty()) {
subscriber.onComplete();
return;
}
for (long i = 0; i < n; i++) {
LocalDate item = list.remove();
subscriber.onNext(item);
}
}
@Override
public void cancel() {
// Mark as delete ; Close resources, etc
}
}Subscriber
public class TimeSubscriber implements Flow.Subscriber<LocalDate> {
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(LocalDate item) {
DayOfWeek dayOfWeek = item.getDayOfWeek();
int days = startAfterDay(dayOfWeek);
LocalDate localDate = item.plusDays(days);
System.out.println(" The completion date is : " + localDate);
subscription.request(1);
}
private int startAfterDay(DayOfWeek dayOfWeek) {
return switch (dayOfWeek) {
case MONDAY -> 2;
case TUESDAY, THURSDAY, WEDNESDAY -> 1;
case FRIDAY -> 5;
case SATURDAY -> 4;
case SUNDAY -> 3;
};
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}Main Method
public static void main(String[] args) {
// First step , Declare a publisher
LinkedList<LocalDate> linkedList = new LinkedList();
linkedList.add(LocalDate.now());
TimePublisher timePublisher = new TimePublisher(linkedList);
// Second parts , Declaration process ,
TimeSubscriber timeSubscriber = new TimeSubscriber();
timePublisher.subscribe(timeSubscriber);
}The second stage
Disassemble the execution process into two processes , Use Processor,
The day of the week is the middle result of the flow , It is both the upstream result and the downstream data source ; Try to write the code
Intermediate processor for calculating the day of the week
Here, the code of the first phase is split directly , therefore Publisher and Subscription unchanged , and subscriber It becomes Processor, Became an intermediate processor
public class TimeProcessor implements Flow.Processor<LocalDate,DayOfWeek> {
private Flow.Subscription subscription;
public TimeProcessor() {
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(LocalDate item) {
DayOfWeek dayOfWeek = item.getDayOfWeek();
emit(dayOfWeek);
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
// ------- Next assembly line ,
private void emit(DayOfWeek dayOfWeek) {
subscribe(daySubscriber);
daySubscription.emit(dayOfWeek);
}
DaySubscription daySubscription;
@Override
public void subscribe(Flow.Subscriber subscriber) {
if (daySubscription == null) {
return;
}
DaySubscription subscription = new DaySubscription((DaySubscriber) subscriber);
this.daySubscription = subscription;
daySubscriber.onSubscribe(subscription);
}
DaySubscriber daySubscriber;
public TimeProcessor downStream(DaySubscriber daySubscriber) {
this.daySubscriber = daySubscriber;
return this;
}
}DaySubscription
Downstream intermediaries
demo In order to save trouble, it is written directly to the publisher's constructor ; But the intermediate state adds a method to send data ; After the data is transmitted, the mediation will call the subscriber to consume the message
public class DaySubscription implements Flow.Subscription {
private final DaySubscriber dayProcessor;
private DayOfWeek dayOfWeek;
public DaySubscription(DaySubscriber daySubscriber) {
this.dayProcessor = daySubscriber;
}
public void emit(DayOfWeek dayOfWeek) {
this.dayOfWeek = dayOfWeek;
request(1);
}
@Override
public void request(long n) {
dayProcessor.onNext(dayOfWeek);
}
@Override
public void cancel() {
}
}DaySubscriber
Downstream subscribers
This place is for simplicity , Back pressure is not used ; Because as demo, No asynchrony is used . therefore onNext Just execute the logic of consumption data
public class DaySubscriber<T> implements Flow.Subscriber<DayOfWeek> {
private Flow.Subscription daySubscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.daySubscription = subscription;
}
@Override
public void onNext(DayOfWeek item) {
int day = switch (item) {
case MONDAY -> 2;
case TUESDAY, THURSDAY, WEDNESDAY -> 1;
case FRIDAY -> 5;
case SATURDAY -> 4;
case SUNDAY -> 3;
};
System.out.printf(" The task begins with : %s , Will be in %d The execution starts after days ", item, day);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}Main
Consider simplicity ; There is only one intermediate processor to be familiar with the basic logic of a response
Essentially, you need to specify the steps , The code is similar to the above flowchart
public static void main(String[] args) {
LinkedList<LocalDate> linkedList = new LinkedList<>();
linkedList.add(LocalDate.now());
TimePublisher timePublisher = new TimePublisher(linkedList);
timePublisher.subscribe(new TimeProcessor().downStream(new DaySubscriber()));
}边栏推荐
- Unknown character set index for field ‘255‘ received from server.
- PHP curl function extension basic usage
- 详解四元数
- 嵌入式接口复习资料
- 腾讯会议号设计的几种猜测
- Giants end up "setting up stalls" and big stalls fall into "bitter battle"
- 有哪些劵商推荐?在线开户安全么?
- Short video enters the hinterland of online music
- laravel之任务队列
- Can postman be integrated into Ci and CD pipelines for automated interface testing?
猜你喜欢

Kotlin 协程 异步 异步流

WebService client request failed can not create a secure xmlinputfactory

FANUC机器人SRVO-050碰撞检测报警原因分析及处理对策(亲测可用)

Analysis on the advantages and disadvantages of the best 12 project management systems at home and abroad

Bilibili×蓝桥云课|线上编程实战赛全新上新!

The Sandbox 与 BAYZ 达成合作,共同带动巴西的元宇宙发展

Stm32-------adc (voltage detection)

“山大地纬杯”第十二届山东省ICPC大学生程序设计竞赛

Solve the problem that slf4j logs are not printed

C# Winform 自定义进度条ProgressBar
随机推荐
What is an applet container
AIX系统月维护查什么(二)
堡垒机安装pytorch,mmcv,mmclassification,并训练自己的数据集
PyQt5_QTableWidget分页单选右键菜单控件
Construction of cache stack FIFO in different application scenarios for PLC data operation series (detailed algorithm explanation)
Task queue of laravel
Bilibili×蓝桥云课|线上编程实战赛全新上新!
The national post office and other three departments: strengthen the security management of personal information related to postal express delivery, and promote the de identification technology of per
C# 读取内存条占用大小,硬盘占用大小
CTF—Go题目复现
How to write and read ASM file system data
3D打印和激光切割流程的初步了解
Nlog详解
Sorry, your USB cable may be wrong!
Eight models of data analysis: detailed PEST model
Kotlin 协程 异步 异步流
2022山东健博会,济南国际大健康产业博览会,中国营养健康展
评估和选择最佳学习模型的一些指标总结
Flutter中的GetX状态管理用起来真的那么香吗?
Can postman be integrated into Ci and CD pipelines for automated interface testing?