Flow API (java.util.concurrent.Flow) ได้แนะนำใน Java 9 . ช่วยให้เข้าใจวิธีต่างๆ ที่ ผู้เผยแพร่ และ ส สมาชิก อินเทอร์เฟซโต้ตอบเพื่อดำเนินการตามที่ต้องการ
โฟลว์ AP ฉันประกอบด้วย ผู้เผยแพร่ สมาชิก การสมัครรับข้อมูล และ โปรเซสเซอร์ อินเทอร์เฟซซึ่งสามารถอิงตามข้อกำหนดสตรีมแบบรีแอกทีฟได้
ในตัวอย่างด้านล่าง เราสามารถใช้ Flow API ได้โดยใช้อินเทอร์เฟซผู้เผยแพร่-สมาชิก
ตัวอย่าง
import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
public class FlowAPITest {
public static void main(String args[]) {
Publisher<Integer> publisherSync = new Publisher<Integer>() { // Create publisher
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
subscriber.onNext(i);
}
subscriber.onComplete();
}
};
Subscriber<Integer> subscriberSync = new Subscriber<Integer>() { // Create subscriber
@Override
public void onSubscribe(Subscription subscription) {
}
@Override
public void onNext(Integer item) {
System.out.println(Thread.currentThread().getName() + " | Received = " + item);
try {
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
publisherSync.subscribe(subscriberSync);
}
} ผลลัพธ์
main | Publishing = 0 main | Received = 0 main | Publishing = 1 main | Received = 1 main | Publishing = 2 main | Received = 2 main | Publishing = 3 main | Received = 3 main | Publishing = 4 main | Received = 4 main | Publishing = 5 main | Received = 5 main | Publishing = 6 main | Received = 6 main | Publishing = 7 main | Received = 7 main | Publishing = 8 main | Received = 8 main | Publishing = 9 main | Received = 9