Reactive WebSocketSession not able to retrieve .closeStatus when connection finishes on doOnComplete or doOnCancel - spring-webflux

I'm trying to retrieve the 'WebSocketSession.closeStatus()'
I refer here to this object: org.springframework.web.reactive.socket.WebSocketSession.
I have tried to retrieve it during the:
**doOnComplete
doOnCancel
doOnTerminate**
Using the code below:
```.doOnComplete(() ->{
webSocketSession.closeStatus().map(x -> {
log.info(x.getReason());
log.info(x.getCode());
});
})```
The code is executed, but nothing is printed.
I did the same for ```.doOnCancel(()-> { webSocketSession.closeStatus()```
The client is a mobile app, some times the client app closes appropriately, sometimes it doesn't. And I need to capture the code.
Thanks.

You need to subscribe to the returned Mono<CloseStatus> i.e.
.doOnComplete(() ->{
webSocketSession.closeStatus().map(x -> {
log.info(x.getReason());
log.info(x.getCode());
}).subscribe();
})

Related

How to test subscribe call of Observable using Mockk?

I have a function in my ViewModel in which I subscribe to some updates, I want to write a test that will check that after the subscribe is triggered, the specific function is called from the subscribe.
Here is how the function looks:
fun subscribeToTablesUpdates() {
dataManager.getTablesList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { tablesList ->
updateTablesState(tablesList)
}
}
And this is the test that I wrote:
#Test
fun subscribeToTablesListTest() {
val mockedTablesList = mockk<List<Table>()
every {
viewModel.dataManager.getTablesList()
} returns Observable.just(mockedTablesList)
viewModel.subscribeToTablesUpdates()
verify {
viewModel.updateTablesState(mockedTablesList)
}
}
The issue is that I receive assertion exception without any another info and I don't know how to fix that.
Edit 1: subscribeToTableUpdates() is calling from the init block of ViewModel.
So basically the test itself was done right, but there were linking issue. Since the function of the VM was called from the init block the subscription happened only once, and that created a situation when at the time when I mocked the data service, the observer was already subscribed to the other service. Since the init block is called only once, there is no way to change the implementation of the data service to that observer.
After all this investigation the one thing which I successfully forgot came to my mind again: extract every external dependencies to constructors, so further you could substitute it for the test without any problems like this.

Vaadin LoginOverlay

I am very new to both java and vaadin. Hope to be able to get some good tips on how I can improve my code.
I would like to rewrite the code below to use Vaadin´s -> LoginOverlay instead of the code below.
As I said, I'm trying to learn so I have used the code for this example: https://www.youtube.com/watch?v=oMKks5AjaSQ&t=1158s
However, LoginOverlay seems to be a better way to display its login part through. As in this example: https://www.youtube.com/watch?v=pteip-kZm4M
So my question is how can you write the code below as a LoginOverlay.
public class LoginView extends Div {
public LoginView(AuthService authService) {
setId("login-view");
var username = new TextField("Username");
var password = new PasswordField("Password");
add(
new H1("Welcome"),
username,
password,
new Button("Login", event -> {
try {
authService.authenticate(username.getValue(), password.getValue());
UI.getCurrent().navigate("home");
} catch (AuthService.AuthException e) {
Notification.show("Wrong credentials.");
}
}),
new RouterLink("Register", RegisterView.class)
);
}
}
I have only come this far to convert the code.
A clarification of the new part of the code. The code does not work. The part with loginOverlay.addLoginListener (event -> probably needs to be written in a different way.
I'm using IntelliJ 2020.3.4 if that is of any help.
public class LoginView2 extends Composite<LoginOverlay> {
public LoginView2(AuthService authService) {
setId("login-view");
LoginOverlay loginOverlay = getContent();
loginOverlay.setTitle("Welcom");
loginOverlay.setDescription("Manage your business tasks");
loginOverlay.setOpened(true);
loginOverlay.addLoginListener(event -> {try {
if(authService.authenticate(username.getValue(), password.getValue());
UI.getCurrent().navigate("home");
} catch (AuthService.AuthException e) {
Notification.show("Wrong credentials.");
}
}),
new RouterLink("Register", RegisterView.class);
}
}
}
}
Super grateful for all the help you can give.
Many thanks to everyone who makes stackoverflow so amazing.
Copy-pasting code snippets with little idea about what the code does is a recipe for disaster, especially when it comes to security.
You have all kinds of errors in your code: misplaced braces, using variables that do not exist, and a RouterLink far from where it belongs.
I understand you've got to start somewhere. I would recommend starting from code that actually compiles, and then gradually adding things, testing what you have so far at every step.
Here are some tips for your LoginView2:
Remove the whole loginOverlay.addLoginListener(...) code, including the authService.authenticate call and the RouterLink. Make sure that you can run the application at this point, and that you can see the login overlay.
Add back the login listener, but for now just show a notification in it. Test that you can run the application, and that if you click Login, your notification is displayed.
loginOverlay.addLoginListener(event -> {
Notification.show("This is working");
});
Implement the authentication. You have a call to authService.authenticate(...) inside an if-statement, but the method does not return anything. Instead, it throws an exception if the authentication fails, hence the try-catch. This means that inside the try { ... } block, any code you put after the authService.authenticate(...) call is only executed if it did not throw an exception, i.e. if the authentication was successful.
There are no username or password variables. The first YouTube video had defined these variables in the form of text fields. With the login overlay, it creates those fields for you, so how do you get the corresponding values from it?

Kotlin - Here Maps - Get address out of callback function

I am attempting to get the address out of the callback function. I have been reading the documentation for CallBacks and some posts but still don't get why this is not working, as at the moment of returning the 'address' variable the callback has already finished.
private fun getAddressForCoordinates(geoCoordinates: GeoCoordinates):String {
address = "unchanged"
val maxItems = 1
val reverseGeocodingOptions = SearchOptions(LanguageCode.EN_GB, maxItems)
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
return address
}
private val addressSearchCallback =
SearchCallback { searchError, list ->
if (searchError != null) {
//showDialog("Reverse geocoding", "Error: $searchError")
Toast.makeText(context, "Error: $searchError", Toast.LENGTH_LONG).show()
return#SearchCallback
}
Toast.makeText(
context,
"Reverse geocoded address:" + list!![0].address.addressText,
Toast.LENGTH_LONG
).show()
address = list[0].address.addressText
}
From your code and comment I assume you are not familiar with the concept of asynchronous execution. That concept was well described here. I'll quote the main point:
When you execute something synchronously, you wait for it to finish
before moving on to another task. When you execute something
asynchronously, you can move on to another task before it finishes.
The fact that search() requires providing a callback and it doesn't simply return search results, is a good indication that it is most probably asynchronous. Invoking it is like saying: "Search for the data in the background and let me know when you have it. This is my email address - please send me my results there". Where email address is your callback. Invoking search() method does not block execution of your code, it does not wait for results - it only schedules searching and returns almost immediately.
Asynchronous processing is usually more tricky than a regular, synchronous code, but in many cases it is more efficient. In your case you can either try to "convert" original async API of the library to sync API that your code expects - but this is not recommended approach. Or you can redesign your code, so it will work asynchronously. For example, instead of doing this:
fun yourMethodThatNeedsAddress() {
val address = getAddressForCoordinates()
doSomethingWithAddress(address)
}
You need to do this:
fun yourMethodThatNeedsAddress() {
scheduleGetAddressForCoordinates() // renamed getAddressForCoordinates()
}
fun addressSearchCallback() {
...
doSomethingWithAddress(address)
}
So, whatever you planned to do with the acquired address, you can't do this straight after you started searching. You need to wait for a callback and then continue with processing of your address from there.
The SearchEngine from the 4.x HERE SDK needs an online connection as it is fetching results from a remote backend. This may take a few milliseconds, depending on your network connection. So, whenever you perform a search request, you need to wait until the callback is called:
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
When you call this, you pass addressSearchCallback as parameter. The implementation for addressSearchCallback can look like in your example. It will be called whenever the operation has finished. If the device is offline, then an error will be shown.
Note that the search() method is not returning any results immediately. These are passed to the callback, which happens asynchronously on a background thread. Thus, your application can continue to work without blocking any UI.
Once results are retrieved, the callback will be executed by the HERE SDK on the main thread.
So, if your code needs to do something with the address result, you have to do it inside the onSearchCompleted() method defined by the SearchCallback. If you write it in plain Java without lambda notation, it is more visible: You create a new SearchCallback object and pass it as parameter to the SearchEngine. The SearchEngine stores the object and executes the object's onSearchCompleted() whenever it thinks it's the right time:
private SearchCallback addressSearchCallback = new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
// Here is the place to do something more useful with the Address object ...!
}
};
I took this from this GitHub code snippet. Note that there is also an OfflineSearchEngine, that works without an internet connection, but for some reason it follows the same pattern and executes the task asynchronously.
private void getAddressForCoordinates(GeoCoordinates geoCoordinates) {
int maxItems = 1;
SearchOptions reverseGeocodingOptions = new SearchOptions(LanguageCode.EN_GB, maxItems);
searchEngine.search(geoCoordinates, reverseGeocodingOptions, new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
}
});
}
SearchEngine, a SearchOptions instance needs to be provided to set the desired LanguageCode. It determines the language of the resulting address. Then we can make a call to the engine's search()-method to search online for the address of the passed coordinates. In case of errors, such as when the device is offline, SearchError holds the error cause.
The reverse geocoding response contains either an error or a result: SearchError and the result list can never be null at the same time - or non-null at the same time.
The Address object contained inside each Place instance is a data class that contains multiple String fields describing the address of the raw location, such as country, city, street name, and many more. Consult the API Reference for more details. If you are only interested in receiving a readable address representation, you can access addressText, as shown in the above example. This is a String containing the most relevant address details, including the place's title.
Please refer to following link for detailed documentation on search() function and parameters associated with it.
https://developer.here.com/documentation/android-sdk-explore/4.4.0.2/dev_guide/topics/search.html

RxJava/RxKotlin: Wait for value to be fetched async and then provide to all subscribers

I have a scenario where I have to fetch some string asynchronously. I would like to create a method where I can listen to when this value is fetched successfully and then provided to the listener.
Now, this can be done easily via many ways including a callback listener or a lambda.
But what do I use so that all subsequent calls to this method, also provide the string back - without having to fetch it again, as it has already been fetched once. So a solution where the listener is still attached but is provided the value right away since it is available.
I know how to do this via old fashioned callback listeners, where the value is stored and then for subsequent calls it can be returned right away via the callback.
But is there a more compact/sophisticated way to do it, let's say via Rx?
Thanks.
I think you can just use cache() operator. It will be something like this:
val value: Single<String> by lazy {
// emulation of your callback
Single.create<String> { emitter ->
Thread.sleep(1000)
println("do some work")
emitter.onSuccess("test")
}.cache()
}
fun main() {
value.subscribe { str -> println(str) }
value.subscribe { str -> println(str) }
value.subscribe { str -> println(str) }
Thread.sleep(2000)
// output:
// do some work
// test
// test
// test
}

Kotlin ConflatedBroadcastChannel.offer() doesn't work?

I am sending a value via MyRepository.myConflatedChannel.offer(myvalue).
I then expect to receive it in collect { } or onEach { } blocks in my ViewModel. However, neither function is invoked. It is as if nothing is passed down the ConflatedBroadcastChannel.
Has anybody seen a similar problem?
Make sure you properly work with receiving values.
If you use the ConflatedBroadcastChannel, you can use either OpenSubscription to get a ReceiveChannel or you can represent it as flow (with asFlow).
Note that consume and consumeEach are terminal, they perform an action and then cancel the channel after the execution of the block. See this.
First case:
val receivingChannel = MyRepository.myConflatedChannel.openSubscription()
// then you can consume values using for example a for loop, e.g.:
launch {
for (value in receivingChannel) {
// do something
}
}
Second case:
val receivingFlow = MyRepository.myConflatedChannel.asFlow()
launch {
receivingFlow.collect {
// do something
}
}