首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactFX -“懒惰”实时搜索文本区域

ReactFX -“懒惰”实时搜索文本区域
EN

Stack Overflow用户
提问于 2016-09-09 02:38:45
回答 2查看 250关注 0票数 2

新的反应式编程在这里。

我试图在JavaFX中用ReactFX实现一个“懒惰”的实时搜索文本区域。这里我的意思是,一旦用户停止输入一秒钟,它就会执行搜索。这方面的代码非常简单:

代码语言:javascript
复制
EventStream<Change<String>> textEvents = EventStreams.changesOf(textArea.textProperty())
.successionEnds(Duration.ofSeconds(1));

然后订阅该事件流和voilà。

但是,如果用户按Enter键,我也希望它立即执行搜索。我不知道如何以一种“反应”的方式做这件事。简单地对Enter键事件执行搜索会导致搜索两次(一个用于键事件,另一个用于文本更改),因此这是我当前的解决方案:

代码语言:javascript
复制
BooleanProperty hasSearched = new SimpleBooleanProperty(false);
EventStream<KeyEvent> enterKeyPressedEvents = EventStreams.eventsOf(textArea, KeyEvent.KEY_PRESSED)
        .filter(k -> k.getCode() == KeyCode.ENTER);
AwaitingEventStream<Change<String>> textEvents = EventStreams.changesOf(textArea.textProperty())
        .successionEnds(Duration.ofSeconds(1));

subs = Subscription.multi(
        //Text changed
        textEvents.subscribe(e -> {
            if (hasSearched.get()) {
                hasSearched.set(false);
                System.out.println("ignored text event");
            } else {
                performSearch(textArea.getText());
            }
        }),

        //Enter key pressed
        enterKeyPressedEvents.subscribe(e -> {
            e.consume();
            if (e.isShiftDown()) {
                textArea.insertText(textArea.getCaretPosition(), "\n");
            } else {
                hasSearched.set(true);
                System.out.println("enter pressed");
                performSearch(textArea.getText());
                if (!textEvents.isPending()) {
                    hasSearched.set(false);
                }
            }
        })
);

我尝试过使用SuspendableEventStream.suspend(),认为它会“删除”所有挂起的事件,但是它没有像预期的那样工作,挂起的事件仍然发出:

代码语言:javascript
复制
EventStream<KeyEvent> enterKeyPressedEvents = EventStreams.eventsOf(textArea, KeyEvent.KEY_PRESSED)
        .filter(k -> k.getCode() == KeyCode.ENTER);
SuspendableEventStream<Change<String>> textEvents = EventStreams.changesOf(textArea.textProperty())
        .successionEnds(Duration.ofSeconds(1)).suppressible();

subs = Subscription.multi(
        //Text changed
        textEvents.subscribe(e -> {
                performSearch(textArea.getText());
        }),

        //Enter key pressed
        enterKeyPressedEvents.subscribe(e -> {
            e.consume();
            if (e.isShiftDown()) {
                textArea.insertText(textArea.getCaretPosition(), "\n");
            } else {
                Guard guard = textEvents.suspend();
                System.out.println("enter pressed");
                performSearch(textArea.getText());
                guard.close();
            }
        })
);

我怎么能想到更好的(更多的反应)?解决办法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-09 03:19:04

这里有一个解决办法。该解决方案的关键部分是观察flatMap内部的文本变化,它具有“重置”文本更改流的作用。

代码语言:javascript
复制
import java.time.Duration;
import java.util.function.Function;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

import org.reactfx.EventStream;
import org.reactfx.EventStreams;

public class AutoSearch extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        TextArea area = new TextArea();

        EventStream<KeyEvent> enterPresses = EventStreams.eventsOf(area, KeyEvent.KEY_PRESSED)
                .filter(k -> k.getCode() == KeyCode.ENTER)
                .hook(KeyEvent::consume);

        EventStream<?> searchImpulse = enterPresses.withDefaultEvent(null) // emit an event even before Enter is pressed
                .flatMap(x -> {
                    EventStream<?> edits = EventStreams.changesOf(area.textProperty())
                                                       .successionEnds(Duration.ofSeconds(1));
                    return ((x == null) ? edits : edits.withDefaultEvent(null))
                            .map(Function.identity()); // just to get the proper type of the result
                });

        searchImpulse.subscribe(x -> System.out.println("Search now!"));

        stage.setScene(new Scene(area));
        stage.show();
    }

}
票数 3
EN

Stack Overflow用户

发布于 2016-09-09 03:08:32

没有经过测试,但如何:

代码语言:javascript
复制
EventStream<KeyEvent> enterKeyPressedEvents = EventStreams.eventsOf(textArea, KeyEvent.KEY_PRESSED)
        .filter(k -> k.getCode() == KeyCode.ENTER);
EventStream<Change<String>> textEvents = EventStreams.changesOf(textArea.textProperty())
        .successionEnds(Duration.ofSeconds(1))
        .filter(c -> ! isAdditionOfNewline(c, textArea.getCaratPosition()));

EventStreams.merge(enterKeyPressedEvents, textEvents)
        .subscribe(o -> performSearch(textArea.getText()));

private boolean isAdditionOfNewline(Change<String> change, int caratPos) {
    // TODO make sure this works as required
    String oldText = change.getOldValue();
    String newText = change.getNewValue();
    if (oldText.length()+1 != newText.length() || caratPos == 0) {
        return false ;
    }

    return oldText.equals(newText.substring(0, caratPos-1) + newText.substring(caratPos));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39403009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档