Changing routines while running

So I’m basically trying to get a loop going. I would like then to change a variable within the loop and have it keep going with the new variable in place. I’m not sure if this is the best way to do this.

(
r = Routine {
    loop {
		
~in.source = {
			//whaterver sound element I'm calling again and again...
};

	        rrand(5, 10).yield;

    }
}.play;
)

So let’s say I change the numbers in rrand and call it again, I find it is running a new Routine alongside the old one. Then r.stop only stops the last running routine.

As I said I want to hear the Routine run, then just improvise through changing the variables, enter (or call) the changes, and have it keep going with the new variables replacing the old, not creating a second Routine on top of the last one.

I hope this makes sense. I’m thankful for other suggestions if this isn’t the best way to use Routine.

Thanks!

Why don’t you use external variables ?

(
~rdmin=2.0;
~rdmax=4.0;
r = Routine {
	loop {
		var w=rrand(~rdmin,~rdmax);
		postf("wait %\n",w);
		w.yield;
		"done".postln;
	}
}.play;
)

// change it
(
~rdmin=5.0;
~rdmax=6.0;
)

r.stop;

Another way is to use Tdef which replace the whole Task (this is like a routine) each time you run the code. You can also define a quant to replace the old routine in sync with tempo

~in = NodeProxy.new; ~in.play;
(
Tdef(\bla, {
	loop {
		~in.source = { SinOsc.ar(rrand(100,210)) * 0.4 };
		rrand(0.5, 3.10).wait; // change wait time and run again
	}
}).play;
)

Thanks! Also a great solution!