Roku Developer Program

Developers and content creators—a complete solution for growing an audience directly.
cancel
Showing results for 
Search instead for 
Did you mean: 
kidasov
Level 7

Use same task iin callback

Hello! I spend so much time for this problem. I want to restart same task in its callback, but it doesn't work. For example I want to create a task to make infinite counter  :
<?xml version="1.0" encoding="UTF-8"?>
<component name="IncVariableTask" extends="Task" xsi:noNamespaceSchemaLocation="https://devtools.web.roku.com/schema/RokuSceneGraph.xsd">
<script type="text/brightscript" uri="pkg:/components/tasks/IncVariableTask/IncVariableTask.brs" />
<interface>

<field id="newValue" type="int" alwaysNotify="true" />
<field id="oldValue" type="int" alwaysNotify="true" />
</interface>
</component>


sub init()
    m.top.functionName = "executeTask"
end sub

function executeTask()
    oldValue = m.top.oldValue
    
    print("oldvalue " + oldValue.toStr())
    
    m.top.newValue = oldValue + 1
    
    print("new value " + m.top.newValue.toStr())
end function


Mainscene.brs
sub init()
    m.task = CreateObject("roSGNode", "IncVariableTask")
    m.task.setField("oldValue", 1)
    m.task.observeField("newValue", "onIncVariable")
    m.task.control = "RUN"
end sub

sub onIncVariable()
    newValue = m.task.newValue
    print("In callback newValue: " + newValue.toStr())    
    
    m.task.unobserveField("newValue")   

    ' trying to rerun task here
    m.task.setField("oldValue", newValue)
    m.task.observeField("newValue", "onIncVariable")    
    m.task.control = "RUN"    
end sub

Output: 
In task oldValue: 1
In callback newValue: 2
In task newValue: 2

What I am doing wrong? Why callback output happens between task operation output? And what's is the correct way to reuse same task in its callback?
Any help highly appreciated!
0 Kudos
2 Replies
kidasov
Level 7

Re: Use same task iin callback

Bumpp
0 Kudos
joetesta
Level 10

Re: Use same task iin callback

I think as soon as the field is changed, Main thread takes over and puts task on back burner.
Depending what you're trying to do, you could alter the timing of when you set m.top field to trigger callback, or possibly recreate and overwrite the task in main each time.
Perhaps just get rid of the last control = run line (control probably already equals run) and update your task field to trigger when the oldvalue is set;
<field id="oldValue" type="int" alwaysNotify="true" onChange="FunctionToRunInTaskBrs"/>

oh and put the observer line before the setfield line in the preceding two lines (ie last lines should look like)
    ' trying to rerun task here
   m.task.observeField("newValue", "onIncVariable") 
    m.task.setField("oldValue", newValue)
 

otherwise task.newValue may be updated before observer starts...
aspiring
0 Kudos