Godot Version
4.2.1
Question
Is it possible to return a “Signal” that immediately emits data?
I have a global singleton that loads data asynchronously, returning a signal that can be awaited to get the data when it is loaded. See below for an example of how this works.
the singleton code:
class Job:
name: String
signal loaded
func _init(name):
self.name = name
func load_data_async(name):
# Encapsulate the work to be done in an inner class
var job = MyJob(name)
# Send the job to a thread pool, which will emit job.loaded when the data is loaded
add_job_to_threadpool(job)
# Return the signal which can be awaited or connected to a slot
return job.loaded
usage somewher else:
var data = await MySingleton.load_data_async(data_name)
This works well. However, I want my singleton to cache data, and if the data is already loaded, immediately return the data rather than sending it to a thread pool. Something like the below:
var cache = {}
func load_data_async(name):
if name in cache:
# Return a signal containing the data, but that immediately emits the data
return ?
var job = MyJob(name)
# The data will be loaded in a thread here, but also added to the cache for subsequent use
add_job_to_threadpool(job)
return job.loaded
func example_usage():
var loaded = MySingleton.load_data_async(data_name)
loaded.connect(_on_data_loaded)
func _on_data_loaded(data):
...
Any ideas? Thanks!