Comments (6)
Let's say you have a source
producer. One way I can think of is:
SignalProducer(value: source)
.delay(1.0, on: UIScheduler())
.times(Int.max)
.flatten(.latest)
.replayLazily(upTo: 1)
from reactiveswift.
I knew there was a nice way to do it. Thanks @andersio
from reactiveswift.
@mfclarke Hmm, after a second thought, the replayLazily
is not in the right place, causing repeated work instead of the intended caching behavior. See the updated snippet. Sorry about the mistake.
Note that it works fine only if one value is cached.
from reactiveswift.
Actually, unfortunately neither solution works (the first one or the updated one). To check it, I'm doing this (with DataFetcher
being a mock that takes 1 second to return dummy data):
let lazyWithCacheExpiry = SignalProducer(value: DataFetcher.fetch())
.delay(1.0, on: QueueScheduler.main)
.times(Int.max)
.flatten(.latest)
.replayLazily(upTo: 1)
print("Starting producer 3 times - all 3 logs should happen once after 1s")
lazyWithCacheExpiry.startWithValues { data in
print("1st returned: \(data)")
}
lazyWithCacheExpiry.startWithValues { data in
print("2nd returned: \(data)")
}
lazyWithCacheExpiry.startWithValues { data in
print("3rd returned: \(data)")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
print("-------------")
print("Get data after cache expiry - should do second fetch")
lazyWithCacheExpiry.startWithValues { data in
print("Returned: \(data)")
}
}
I also have a print
in my mock fetcher to verify it only fetches once.
I get this output:
Starting producer 3 times
Then this repeats a random number of times, from DataFetcher.fetch
(from 2 to ~10):
Performing fetch
Eventually we get:
1st returned: ["a": 1]
2nd returned: ["a": 1]
3rd returned: ["a": 1]
Which will then repeat every 1s.
Always 10s after running this appears:
-------------
Get data after cache expiry - should do second fetch
Immediately followed by:
Returned: ["a": 1]
What I think I need after considering your approach is 2 producers. One doing the work with replayLazily
assigned to one var
and another that is started when the owner object is created which replaces the replayLazily
producer every n seconds using delay
and times
. The downside to this approach though is if the replayLazily
var
is used in another context, for example with a .on
. This will never get replaced, since it's already been copied.
from reactiveswift.
Yeah, it does not invalidate the cached value upon expiry, and have subscriptions after the expiry to wait for the new value. It just starts a request upon expiry so that eventually the cached value is updated.
Maybe it is worth to have something like replayLazily(upTo:timeout:)
.
from reactiveswift.
Ahh I see. That would be kind of cool to have a replayLazily(upTo:timeout:)
. I'd be more than happy to code it up if it's something you guys would like to have? I might need a little bit of hand holding because I haven't been using RAC that long, but would love to have a shot at it!
Here's where I've landed with the issue though:
class DataProvider {
var producer = DataProvider.buildProducer()
private var replacerDisposable: Disposable?
init(withExpiryInterval expiryInterval: TimeInterval) {
replacerDisposable = QueueScheduler.main.schedule(after: Date(), interval: expiryInterval) { [weak self] in
self?.producer = DataProvider.buildProducer()
}
}
private static func buildProducer() -> SignalProducer<MyData, MyFetchError> {
return DataFetcher.fetch().replayLazily(upTo: 1)
}
}
It's neat enough for my purposes, and doesn't leak state so that's a plus.
from reactiveswift.
Related Issues (20)
- Strong reference to observer leads to signal not getting interrupted HOT 1
- observing disposed events HOT 1
- Release 6.6.0 requires Swift 5.3 and therefore Xcode 12.x
- Using "<~" binding function with Signal.Observers causes memory leaks. HOT 3
- Using old xcconfig causing problems with Carthage & Apple Silicon macOS builds
- Support await / AsyncSequence HOT 13
- Playground does not work HOT 1
- Hello, ask a question about Disposable, thanks HOT 1
- What's means 'targeting' in QueueScheduler? HOT 2
- Signal.merge reported issue after migrating from ReactiveSwift from 4.0.0 -> 6.6.0 HOT 2
- xCode13 CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
- Usage with SwiftUI HOT 4
- Could not find module 'ReactiveSwift' for target 'arm64-apple-ios-simulator' HOT 2
- [BUG] XCode 14 beta 3 - bitcode issue HOT 1
- Is it planned to add count argument to `collect(every:on:skipEmpty:discardWhenCompleted:)`?
- Adopt OSAllocatedUnfairLock on iOS 16 HOT 9
- Add support for mapping Property/MutableProperty types to a Binding
- Signal triggered by phone call when device is closed HOT 3
- Infinite recursion in observeSwitchToLatest() HOT 3
- EXC_BAD_ACCESS Crashes occur in xcode15 HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from reactiveswift.