如何在Swift中访问KMMShared MutableStateFlow对象

ttp71kqs  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(129)

我有一个带有MutableStateFlow的KmmShared单例类,它在Android上工作得很好。我需要知道访问这个Singleton类的最佳方法,它的MutableStateFlow变量在SwiftUI应用程序中更新。

class MySingeltonClass {
    private val _selectedType: MutableStateFlow<MyEnum> = MutableStateFlow(getUserPrefsType())
    var selectedType = _selectedType.asStateFlow()

    private fun getUserPrefsType() : MyEnum {
        // Get Enum from DB
    }

    fun setType(scheme: MyEnum) {
        // Set Enum in DB
        _selectedType.value = scheme
    }

    companion object {
        private lateinit var instance: MySingeltonClass
        fun getInstance(): MySingeltonClass {
            if (!this::instance.isInitialized) {
                instance = MySingeltonClass()
            }
            return instance
        }

    }
}

enum class MyEnum {
    TYPEA, TYPEB, TYPEC;
}

如果我可以有一个MySingeltonWrapperClass与一个@Published var selectedType或一个@ObservedObject private var selectedType是我试图在Swift中实现的东西。

qvk1mo1f

qvk1mo1f1#

这是个很棘手的主题。SwiftUI应用程序中Flow/StateFlow的主要问题在于KotlinSwift互操作性<->。因为它有几个限制:

  • 互操作性不适用于通用接口
  • 我们需要在特定的CoroutineScope中启动流,以便能够取消作业

好文章更好理解:onetwo
有几种可用的解决方法:

1.将Flow封装到Kotlinclass中。你可以在official KMM sample repo中找到这种技术的很好的例子。

首先,author introduces new classCFlow

fun interface Closeable {
    fun close()
}

class CFlow<T: Any> internal constructor(private val origin: Flow<T>) : Flow<T> by origin {
    fun watch(block: (T) -> Unit): Closeable {
        val job = Job()

        onEach {
            block(it)
        }.launchIn(CoroutineScope(Dispatchers.Main + job))

        return Closeable { job.cancel() }
    }
}

internal fun <T: Any> Flow<T>.wrap(): CFlow<T> = CFlow(this)

然后在SwiftUI中使用它:

class ObservableFeedStore: ObservableObject {
    @Published public var state: FeedState =  FeedState(progress: false, feeds: [], selectedFeed: nil)
    
    var stateWatcher : Closeable?

    init(store: FeedStore) {
        stateWatcher = self.store.watchState().watch { [weak self] state in
            self?.state = state
        }
    }
    
    deinit {
        stateWatcher?.close()
    }
}

2.使用特殊库,如KMP-NativeCoroutines

当你设置这个库时,你可以为你的KotlinFlow/StateFlow创建Swift AnyPublisher

let publisher = createPublisher(for: yourFlow)

3.不要使用Flow/StateFlow。你可以用简单的替代品。看看Decompose project,它是Valueclass

abstract class Value<out T : Any> {
    abstract val value: T
    abstract fun subscribe(observer: (T) -> Unit)
    abstract fun unsubscribe(observer: (T) -> Unit)
}

你仍然可以很容易地在你的Compose应用程序中使用它来获得Statesample from Decompose

@Composable
fun <T : Any> Value<T>.subscribeAsState(policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy()): State<T> {
    val state = remember(this, policy) { mutableStateOf(value, policy) }

    DisposableEffect(this) {
        val observer: (T) -> Unit = { state.value = it }

        subscribe(observer)

        onDispose {
            unsubscribe(observer)
        }
    }

    return state
}

在SwiftUI中,你可以使用ObservableValuehelper from Decompose

public class ObservableValue<T : AnyObject> : ObservableObject {
    private let observableValue: Value<T>

    @Published
    var value: T

    private var observer: ((T) -> Void)?
    
    init(_ value: Value<T>) {
        observableValue = value
        self.value = observableValue.value
        observer = { [weak self] value in self?.value = value }
        observableValue.subscribe(observer: observer!)
    }

    deinit {
        observableValue.unsubscribe(observer: self.observer!)
    }
}

相关问题