Android Question Resumable sub already completed

Alessandro71

Well-Known Member
Licensed User
Longtime User
I have a background task (actually a Bluetooth device scan) that I have to wait completion.
To not forcing the user to wait for it, I coded it as a resumable sub, run it and, while it runs, perform some user interaction.

B4X:
Dim BLEScan As Object    'for waiting on
BLEScan = Globals.bluetoothDevs.ScanBLE 'start background scanning
' ...
'user interaction code that have variable completion time
' ...
ToastMessage.ShowProgress("Scanning Bluetooth")
Wait For (BLEScan) Complete (success As Boolean)
ToastMessage.HideProgress
If the user completes the iteraction before the scan is completed, the Wait For works as intended, waiting for the sub to complete before proceeding.
If the user is slow and the resumable sub completes beforehand, the Wait For causes a crash with

Resumable sub already completed

What's the best way to deal with such a case?
 

agraham

Expert
Licensed User
Longtime User
Two possible ways

1) Set a flag in Globals before invoking ScanBLE and clear it in ScanBLE as it ends and check that flag before invoking Wait For. This should work without synchronisation problems as all the code involved runs on the main thread.

2) Put the Wait For in a Try ... Catch block.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
That raises the question of when does the ResumableSub get freed for garbage collection?
Like any other object, after there are no more live references. In the case of resumable subs, the event system also keeps a reference to the resumable sub until the event is raised (this is not 100% accurate but close to it).
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
If the ResumableSub has completed is there then the danger of attempting to check Complete after it has been garbage collected?

when do you mean "then" ?
with ResumableSub you dont check if the sub completed you wait until it is then you perform your task. if you want to know in a later phase if that event was raised true or false you can use a global variable for that.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
when do you mean "then" ?
Sorry, you have misunderstood the point of this question. A ResumableSub is an instance of a class. As such it will be garbage collected when no references to it exist after it completes. I was asking Erel if there was a possibility that the ResumableSub could already be garbage collected before Complete on it was invoked.
 
Upvote 0
Top