https://kotlinlang.org logo
Title
s

Sam

01/30/2023, 1:14 PM
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

Andrei Salavei

01/30/2023, 1:15 PM
Does expect/actual implementation help you here?
s

Sam

01/30/2023, 1:16 PM
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

Andrei Salavei

01/30/2023, 1:19 PM
But you can use the same approach to implement the
expect/actual
method that returns cache directory path for each platform. Do you?
s

Sam

01/30/2023, 1:20 PM
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
val paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true);
val cacheDirectory = paths.first()
v

Vidmantas Kerbelis

01/30/2023, 1:38 PM
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

Sam

01/30/2023, 1:47 PM
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

Vidmantas Kerbelis

01/30/2023, 1:54 PM
In most cases for Android it’s just:
context.cacheDir (File), so for the path, it would be cacheDir.absolutePath (or relativePath)
s

Sam

01/30/2023, 1:55 PM
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

Vidmantas Kerbelis

01/30/2023, 1:56 PM
To access the Android resource system you need to have
Context
, so you must do it on the Android platform’s side sadly
s

Sam

01/30/2023, 1:58 PM
No probs, thanks!
j

Jeff Lockhart

01/30/2023, 11:49 PM
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).