开发者

Will you create a service for Rx.Observable?

开发者 https://www.devze.com 2023-04-07 15:37 出处:网络
I have the following code in VM.. Observable .Timer(remainingTimeSpanForNextHour, TimeSpan.FromHours(1))

I have the following code in VM..

Observable
                    .Timer(remainingTimeSpanForNextHour, TimeSpan.FromHours(1))
                    .Timestamp()
            开发者_Go百科        .Subscribe( x => FillBookingData());

My questions are ~

  1. Do you think we need to test this code? Would it be like we are trying to test Rx if we are planning to test this code? maybe. we should just test only this value "remainingTimeSpanForNextHour"

  2. Let's say we should test this code. Do you think it's good idea to create the service like IObservableService ?


It's always a good idea to test your code, but with observables it can be a little hard if your code is all in the one method or code block.

You should try to separate out the components of this query - and for me there are three components:

  1. Parameters
  2. Observable
  3. Observer

So write tests to ensure you get the right parameter values coming in.

Then write tests that ensure that your query produces values according to a similar set of input values. I wouldn't write a test that has to wait an hour for a value to arrive, so change hours to seconds, etc.

Then write tests that make sure that the observer works.

Now, as far as writing an IObservableService interface/implementation I think that is not a good thing. I'd instead focus on writing one or more service that abstract away what you're trying to do on a functional basis so that you are being DRY (Don't Repeat Yourself).

So, I would think an ITimerService might be useful.

public interface ITimerService
{
    IDisposable Subscribe(TimeSpan dueTime, TimeSpan period, Action action);
}

Clearly it is designed to fit in with Rx - the signature is similar to Observable.Timer crossed with IObservable.Subscribe. It would use your existing query, just made to use the input parameters.

You should find testing this code to be quite easy.

Let me know if this is a good starting point for you.


Testing a timer is easy using Virtual Time - you can ignore the ReactiveUI bits, use AdvanceTo and figure out a way to inject the IScheduler you're using into your code (both Timer() and Timestamp() must be given your TestScheduler objects)

Even though this seems like a pain, the end result is that you can test code that will normally take time to execute, instantly and your tests will have the same result every time.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号