Skip to content

Multiplatform support #91

@emilbutiri

Description

@emilbutiri

Hi! Now that the Jetpack lifecycle and view model libraries have multiplatform support, I was wondering if this library could be made multiplatform compatible. In my case, I'm thinking of iOS, and being able to scope a ViewModel to a SwiftUI View.
I know of two solutions so far:

  1. KMP-ObservableViewModel solution where using the @StateViewModel annotation will take care of the lifecycle and ensure the view model is cleared when the View is destroyed

  2. This solution, that I'm currently using myself, and seems to work fine, though there's a bit of boilerplate involved (maybe because I don't know any better):

In the iOS app, create a ViewModelOwner class that implements the ViewModelOwner interface. This requires the shared module to export the Jetpack viewmodel library.

// ViewModelStoreOwner.swift

import shared 

class ViewModelStoreOwner: shared.ViewModelStoreOwner {
    internal let viewModelStore = ViewModelStore()
    
    fileprivate func put<VM: ViewModel>(_ vm: VM) {
        viewModelStore.put(key: VM.self.description(), viewModel: vm)
    }
    
    // This is called when the View containing this object is destroyed
    deinit {
        viewModelStore.clear()
    }
}

// A helper function to create a ViewModel with an owner
func viewModel<VM: ViewModel>(owner: ViewModelStoreOwner, _ factory: () -> VM) -> VM {
    let vm = factory()
    owner.put(vm)
    return vm
}

Then in a View implementation:

// SomeView.swift

import SwiftUI

struct SomeView: View {
    private let owner = ViewModelStoreOwner()
    private let vm: SomeViewModel

    init() {
        vm = viewModel(owner: owner) {
            SomeViewModel()
        }
    }

    var body: some View {
        // etc
    }
}

I'm using the second method because I don't need all the other stuff KMP-ObservableViewModel offers - I prefer to use SKIE to handle Flows.

But I started wondering if it wouldn't be possible to make viewModelScoped() work inside a SwiftUI View.

Best regards,
/Emil

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions