B4J Tutorial [B4X] Resumable Subs - Sleep / Wait For

Not open for further replies.


Licensed User
How do you deal with resumable subs inability to return values?

I have a sub that benefits from using Sleep() as a timeout delay (while waiting on Astreams NewData event which sets a DataReceived Flag if data was received). The Sleep command pauses the resumable sub, allows other message events to be processed (i.e. NewData) and eventually the Sleep finishes and the resumable sub continues execution after the Sleep() command.
After the Sleep delay I check the DataReceived Flag and I would like to return a boolean true/false flag to the resumable sub caller.

I could use a global flag which is checked after calling the resumable sub but I'm just wondering if there is a better way that I haven't thought of.

Note that I understand why the resumable sub can't return data to the caller ("Whenever Sleep or Wait For are called, the current sub is paused. This is equivalent to Return" and "Calling Sleep or Wait For is equivalent to calling Return from the caller sub perspective."

How to return data to resumable sub caller?


Licensed User
You can call Sleep(0) for the shortest pause. This can be used to allow the UI to be refreshed. It is a good alternative to DoEvents (which doesn't exist in B4J and B4i and should be avoided in B4A).
I fear that you cannot replace DoEvents with Sleep(0) to allow refreshing the GUI because Sleep, even if the time is set to 0, returns control to calling routines.

So, I don't see other good alternative to DoEvents.


Active Member
Licensed User

I have a problem

I have this part of code

Sub Start

ProgressDialogShow2("Wait Please",True)

....other code....


...bla bla bla

End Sub

Sub Wait(MilliSecondi As Int)
   Dim Ti As Long
   Ti = DateTime.Now + (MilliSecondi)
   Do While DateTime.Now < Ti
End Sub

If I remove DoEvents, ProgressDialog does not appear
I tried to replace DoEvents with Sleep(0) but it does not work

Any tips?

luciano deri

Active Member
Licensed User
I don't think that you are using Wait For correctly. It is not needed in the code you posted.

Example of using Sleep to update the progress bar inside a long loop:
Sub SubThatDoesAVeryLongCalculation
   Dim mx As Long = 100000000
   Dim i As Long
   For i = 1 To mx
     If i Mod 10000 = 0 Then
       ProgressDlg.ProgressUpdate(i * 100 / mx)
     End If
End Sub
Note that I made a few changes to your project. See the attachment.
Is there something of similar for B4A?
Not open for further replies.