-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloModel.java
More file actions
74 lines (65 loc) · 2.4 KB
/
HelloModel.java
File metadata and controls
74 lines (65 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.example;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.function.Consumer;
public class HelloModel {
private final NtfyConnection connection;
private final ObservableList<NtfyMessageDto> messages = FXCollections.observableArrayList();
private final StringProperty messageToSend = new SimpleStringProperty("");
public HelloModel(NtfyConnection connection) {
this.connection = connection;
startReceiving();
}
private void startReceiving() {
connection.receive(incoming -> {
if (incoming == null || incoming.message() == null || incoming.message().isBlank()) {
return;
}
runOnFx(() -> messages.add(incoming));
});
}
public void sendMessageAsync(Consumer<Boolean> callback) {
String msg = messageToSend.get();
if (msg == null || msg.isBlank()) {
callback.accept(false);
return;
}
try {
connection.send(msg, success -> {
if (success) {
runOnFx(() -> {
if (msg.equals(messageToSend.get())) {
messageToSend.set("");
}
});
callback.accept(true);
} else {
callback.accept(false);
}
});
} catch (Exception e) {
// FÅNGA ALLA EXCEPTIONS HÄR!
System.err.println("Exception during send: " + e.getMessage());
callback.accept(false);
}
}
private static void runOnFx(Runnable task) {
try {
if (Platform.isFxApplicationThread()) {
task.run();
} else {
Platform.runLater(task);
}
} catch (Exception e) {
task.run(); // fallback i tester
}
}
public ObservableList<NtfyMessageDto> getMessages() { return messages; }
public String getMessageToSend() { return messageToSend.get(); }
public StringProperty messageToSendProperty() { return messageToSend; }
public void setMessageToSend(String v) { messageToSend.set(v); }
public String getGreeting() { return "Welcome to ChatApp"; }
}