gpt4 book ai didi

c# - 允许 Firebase Xamarin 实时流式传输

转载 作者:行者123 更新时间:2023-11-30 23:14:39 25 4
gpt4 key购买 nike

我正在 Xamarin 中构建一个具有实时 Firebase 数据库集成的跨平台应用程序。我正在使用 Firebase C# library FirebaseDatabase.net .在 FibrebaseDatabase.net 文档中,为了启用实时流式传输,它注意到调用例如:

var firebase = new FirebaseClient("https://dinosaur-facts.firebaseio.com/");
var observable = firebase
.Child("dinosaurs")
.AsObservable<Dinosaur>()
.Subscribe(d => Console.WriteLine(d.Key));

但是,为了在 Xamarin 中实现最大程度的代码重用,我需要从共享项目中调用它,而不是在每个独立的 iOS 和 Android 应用程序中调用它。我认为唯一的方法是同步的,因此不允许从我的 firebase 数据库进行实时监控/更新。

我如何创建和调用一个方法以允许从另一个类中异步监听此可观察对象?

最佳答案

如果这是特定于平台的 API,您将必须在各个应用项目中进行这些调用,但您可以使用 DependencyService (如果使用 Xamarin.Forms)从您的共享代码发起对平台特定代码的调用。如果不使用 Xamarin.Forms,您将需要使用一些控制反转库来进行依赖注入(inject)。

来自上面的链接:

Xamarin.Forms apps need three components to use DependencyService:

Interface – The required functionality is defined by an interface in shared code.

Implementation Per Platform – Classes that implement the interface must be added to each platform project.

Registration – Each implementing class must be registered with DependencyService via a metadata attribute. Registration enables DependencyService to find the implementing class and supply it in place of the interface at run time.

Call to DependencyService – Shared code needs to explicitly call DependencyService to ask for implementations of the interface.

Note that implementations must be provided for each platform project in your solution. Platform projects without implementations will fail at runtime.

注意事项:

  1. 在您的共享代码中创建一个接口(interface),其中包含您将调用的方法,这些方法将运行平台特定的代码

  2. 在您的平台特定项目中创建类,以实现在步骤 1 中创建的接口(interface)。然后使用您需要运行的平台特定代码在接口(interface)中实现方法。

  3. 接口(interface)的每个实现都需要使用元数据属性向 DependencyService 注册。以下代码注册了 Windows Phone 的实现:

    [assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]

它位于步骤 2 中创建的平台特定类中的类声明之上。传递给 typeof 方法的参数是该类的名称。

  1. 为每个平台设置通用接口(interface)和实现后,使用 DependencyService 在运行时获得正确的实现:

    DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");

此调用是根据您的共享代码和类型参数进行的,ITextToSpeech 是您在步骤 1 中创建的接口(interface)的名称。

如果您没有使用 Xamarin.Forms,请搜索控制反转库并按照提供的文档了解如何使用它。

关于c# - 允许 Firebase Xamarin 实时流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com