Skip to content

Q: Safe way to preload RiveFile outside of Compose context? #438

@elvisfromsouth

Description

@elvisfromsouth

Background

I'm working on pre-loading Rive files in advance to avoid loading delays during runtime. I need to do this outside of a Compose context.

Previous Approach

I previously used this approach:

val file = context.resources.openRawResource(fileId).use { File(it.readBytes()) }

However, this consumes too much memory for our use case.

Current Workaround

I've discovered that using RiveWorker with RiveFile.fromSource() reduces memory consumption significantly. However, RiveWorker appears to be Compose-specific. I've implemented a workaround that seems to work but feels like a hack:

suspend fun preloadRiveFile(@RawRes fileId: Int): RiveFile? {
    val riveWorker = RiveWorker()
    val riveFile = context.resources.openRawResource(fileId).use {
        RiveFileSource.Bytes(it.readBytes())
    }

    val riveFileResult = coroutineScope {
        val file = async {
            RiveFile.fromSource(riveFile, riveWorker)
        }

        while (file.isActive) {
            delay(100)
            riveWorker.pollMessages()
        }

        file.await()
    }
    
    return when (riveFileResult) {
        is Result.Success<RiveFile> -> riveFileResult.value
        else -> null
    }
}

Questions

  1. Is there a recommended/safe way to preload RiveFile instances outside of Compose?
  2. Is my workaround with RiveWorker.pollMessages() in a coroutine safe for production use?
  3. Are there any plans to provide an official API for pre-loading files for non-Compose contexts?

Any guidance would be greatly appreciated! 🙏

Environment:

Rive Runtime: 11.1.2
Platform: Android
Language: Kotlin

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions