Is there a simple way of accessing the cache directory path from common kotlin code, without passing...
s
Is there a simple way of accessing the cache directory path from common kotlin code, without passing it through from iOS/Android? I want to write some common caching logic that reads and writes from files in the cache directory
a
Does expect/actual implementation help you here?
s
Yeah so I can write file writing/reading logic using
expect/actual
implementations easily enough, it's getting hold of the directory path to write to that I'm struggling with
a
But you can use the same approach to implement the
expect/actual
method that returns cache directory path for each platform. Do you?
s
That's my current question? Is there a way of accessing those directory paths from within the common module (even if that is in the
androidMain
&
iOSMain
source sets?
I think I have a solution on iOS
Copy code
val paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true);
val cacheDirectory = paths.first()
v
Well, if you want to just get the path or something, then
expect/actual
is your friend here. If you want to get a
File
and do something with it in common code. So CRUD operations, or w/e.. Then you probably need something like Okio and use
FileSystem
to open the appropriate files from the cache.
s
As I said I know I can use expect/actual to execute platform specific code, the issue actually getting hold of the correct path. The snippet above correctly gets the cache directory on iOS, does anyone know of an android equivilent ?
v
In most cases for Android it’s just:
Copy code
context.cacheDir (File), so for the path, it would be cacheDir.absolutePath (or relativePath)
s
I'm in in common code here though so don't have easy access to a context (I'm building a library and ideally don't want to make the user pass in the context manually on Android). Context would defo be the way to go in native android
v
To access the Android resource system you need to have
Context
, so you must do it on the Android platform’s side sadly
s
No probs, thanks!
j
korio has a nice way of handling the Android
Context
in common code. It embeds the Android
Context
within the coroutine context, which then can be used by Android actual suspend functions on file systems objects like cacheVfs. You just need to call
withAndroidContext(context)
from the Android code the calls the common code (example).
787 Views