【问题标题】:Understanding generics and how了解泛型以及如何使用
【发布时间】:2022-01-04 00:43:22
【问题描述】:

我是一家公司的新手,正在尝试了解使用过的仿制药。模型的设置包含

var selectedChannel: Driver<Channel> { get }

@available(*, deprecated, message: "Use driver selectedChannel")
var selectedChannelValue: Channel { get }

在代码中的某个时刻使用了selectedChannelValue.id,但它显示了警告消息Use driver selectedChannel。我明白这一点。好的,它仍然可以完成这项工作,但之前的一位程序员出于某种原因弃用了它。

如何重写代码行,以便我得到selectedChannel.id,正如弃用消息所暗示的那样?当我使用selectedChannel.id 时,会出现错误消息Value of type 'Driver&lt;Channel&gt;' (aka 'SharedSequence&lt;DriverSharingStrategy, Channel&gt;') has no member 'id'。如何解开SharedSequence

编辑: channel 结构如下所示:

public struct Channel: Codable {
    public let id: String    // e.g. "1111111"

driverRxCocoa 中设置为:

public typealias Driver<Element> = SharedSequence<DriverSharingStrategy, Element>

public struct DriverSharingStrategy: SharingStrategyProtocol {
    public static var scheduler: SchedulerType { return SharingScheduler.make() }
    public static func share<Element>(_ source: Observable<Element>) -> Observable<Element> {
        return source.share(replay: 1, scope: .whileConnected)
    }
}
extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
    /// Adds `asDriver` to `SharingSequence` with `DriverSharingStrategy`.
    public func asDriver() -> Driver<Element> {
        return self.asSharedSequence()
    }
}

【问题讨论】:

  • 如果不了解 Driver 和 Channel 类型的样子,就不可能说出来。我会假设类似于 selectedChannel.channel.id 但这是一个猜测。

标签: swift generics typescript-generics rx-swift rx-cocoa


【解决方案1】:

通过将 Channel 包装在 Driver 中,代码告诉您它是异步的。所以当你查询它时它可能还不存在,当你观察它时它可能会改变。你用drive 方法观察它:

selectedChannel
    .drive(onNext: { channel in
        // you can use channel.id here.
    })
    .disposed(by: disposeBag)

但是您不能只将 id 保存在闭包之外的某个 var 中并期望一切正常。需要 id 的代码也必须是该闭包(或在从该闭包调用的函数中。)

请注意,您可能还需要在此代码所在的类中创建一个处理包。

DriverObservable 的一种。您应该阅读如何使用这些构造,但出于这些目的,您可以将其视为一种封装在对象中的回调闭包。

【讨论】:

  • 这正是我所需要的!我开始阅读 raywenderlich 教程,但 .drive 是解决我的问题的关键。可以在 .driver 闭包中嵌套 .subscribe{ event in 吗?
  • 这取决于上下文,但总的来说答案是否定的。将驱动器/绑定/订阅嵌入到另一个驱动器/绑定/订阅中是应该避免的代码异味。
猜你喜欢
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多