B4J Question Need help with WaitFor [solved]

Didier9

Well-Known Member
Licensed User
Longtime User
I have not had much success using WaitFor
At the moment, I want to use it to trap either one of two boolean flags after I send a command via AStream.
One flag is set when I received a message via AStream_NewData the other is set in a TimeOutTimer_Tick event if the command times out.
So I would like to use something like this:
B4X:
WaitFor( DataReceived = True Or TimedOut = True )
Obviously that syntax does not work but it gives you the idea. I do not know how to formulate it.
At the moment, I just have a Do While loop with Sleep(0) and that works but that is not very elegant when WaitFor is right there seemingly intended to fix just that....
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Untested example:

B4X:
'usage
ReadData(5000)
Wait For DataReceived (Success As Boolean, Data() As Byte)


Sub ReadData (Timeout As Int)
 Dim b() As Boolean = Array As Boolean(False)
 TimeOutImpl(Timeout, b)
 Wait For Astream_NewData(Data() As Byte)
 If b(0) = false Then CallSubDelayed3(Me, "DataReceived", True, Data)
 b(1) = true
End Sub

Sub TimeOutImpl(Duration As Int, b() As Boolean)
 Sleep(Duration)
 If b(0) = false Then CallSubDelayed3(Me, "DataReceived", False, Null)
 b(1) = true
End Sub
 
Upvote 0

Didier9

Well-Known Member
Licensed User
Longtime User
OK, I think I understand, finally.
The DataReceived() bit following the first Wait For is actually the declaration for the DataReceived() function, which is called by the CallSubDelayed3() calls, and whatever follows that declaration can use the variables Success and Data(). In essence, that function takes over from whatever code was before the Wait For.

I thought DataReceived() was some function that was supposed to be defined somewhere else, and I could not see where it was defined...

Thank you a lot, that was not clear at all reading the documentation, probably because I had preconceived ideas of how it "should" work, based on my experience with proto-threads in C...

So to summarize, there is no way to use boolean flags in a Wait For construct as I asked in the original post?
 
Upvote 0

Didier9

Well-Known Member
Licensed User
Longtime User
It makes sense when I think of it. The main difference between the Do While Sleep(0) I was using and Wait For is that Wait For completely stops the processing of that function until the even is called, where the Do While keeps churning code until the condition is met.
 
Upvote 0
Top